The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Aes128CFB.cs 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Teknik.Utilities.Cryptography
  9. {
  10. public static class Aes128CFB
  11. {
  12. public static byte[] Encrypt(byte[] text, byte[] key)
  13. {
  14. int blockSize = 128;
  15. int keySize = 128;
  16. // Encode the text
  17. string textEnc = Convert.ToBase64String(text);
  18. byte[] textBytes = Encoding.UTF8.GetBytes(textEnc);
  19. // cipherArray
  20. int cipherLen = (blockSize / 8) + textEnc.Length;
  21. byte[] cipherText = new byte[cipherLen];
  22. Array.Clear(cipherText, 0, cipherLen);
  23. // Create the IV needed for this operation
  24. string ivStr = StringHelper.RandomString(blockSize / 8);
  25. byte[] ivBytes = Encoding.UTF8.GetBytes(ivStr);
  26. // copy IV to the cipher text start
  27. ivBytes.CopyTo(cipherText, 0);
  28. // Process the cipher
  29. ProcessCipher(true, textBytes, key, ivBytes, blockSize, keySize, ref cipherText, blockSize / 8);
  30. return cipherText;
  31. }
  32. public static byte[] Decrypt(byte[] text, byte[] key)
  33. {
  34. int blockSize = 128;
  35. int keySize = 128;
  36. // Grab the IV and encrypted text from the original text
  37. byte[] ivBytes = text.Take(blockSize / 8).ToArray();
  38. text = text.Skip(blockSize / 8).Take(text.Length - (blockSize / 8)).ToArray();
  39. // Process the cipher
  40. ProcessCipher(false, text, key, ivBytes, blockSize, keySize, ref text, 0);
  41. string encodedText = Encoding.UTF8.GetString(text);
  42. return Convert.FromBase64String(encodedText);
  43. }
  44. public static void ProcessCipher(bool encrypt, byte[] text, byte[] key, byte[] iv, int blockSize, int keySize, ref byte[] output, int offset)
  45. {
  46. using (var cipher = new RijndaelManaged())
  47. {
  48. cipher.BlockSize = blockSize;
  49. cipher.KeySize = keySize;
  50. cipher.Mode = CipherMode.CFB;
  51. cipher.FeedbackSize = 8;
  52. cipher.Padding = PaddingMode.None;
  53. cipher.Key = key;
  54. cipher.IV = iv;
  55. using (var encryptor = (encrypt) ? cipher.CreateEncryptor() : cipher.CreateDecryptor())
  56. using (MemoryStream ms = new MemoryStream())
  57. using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
  58. using (var bw = new BinaryWriter(cs, Encoding.UTF8))
  59. {
  60. bw.Write(text);
  61. bw.Close();
  62. ms.ToArray().CopyTo(output, offset);
  63. }
  64. }
  65. }
  66. }
  67. }