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.

AES.cs 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace Teknik.Utilities.Cryptography
  5. {
  6. public static class AES
  7. {
  8. public static byte[] Encrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  9. {
  10. using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
  11. {
  12. return Encrypt(cipher, value);
  13. }
  14. }
  15. public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  16. {
  17. using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
  18. {
  19. return Decrypt(cipher, value);
  20. }
  21. }
  22. public static byte[] Encrypt(RijndaelManaged cipher, byte[] value)
  23. {
  24. byte[] encryptedBytes;
  25. using (var encryptor = cipher.CreateEncryptor())
  26. using (MemoryStream ms = new MemoryStream())
  27. using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
  28. using (var bw = new BinaryWriter(cs, Encoding.UTF8))
  29. {
  30. bw.Write(value);
  31. bw.Close();
  32. encryptedBytes = ms.ToArray();
  33. }
  34. return encryptedBytes;
  35. }
  36. public static byte[] Decrypt(RijndaelManaged cipher, byte[] value)
  37. {
  38. byte[] decryptedBytes;
  39. using (var decryptor = cipher.CreateDecryptor())
  40. using (MemoryStream ms = new MemoryStream())
  41. using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
  42. using (var bw = new BinaryWriter(cs, Encoding.UTF8))
  43. {
  44. bw.Write(value);
  45. bw.Close();
  46. decryptedBytes = ms.ToArray();
  47. }
  48. return decryptedBytes;
  49. }
  50. public static RijndaelManaged CreateCipher(byte[] key, byte[] iv, int keyLength, int blockSize, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  51. {
  52. RijndaelManaged cipher = new RijndaelManaged();
  53. cipher.Mode = mode;
  54. cipher.Padding = paddingMode;
  55. cipher.Key = key;
  56. cipher.IV = iv;
  57. cipher.KeySize = keyLength;
  58. cipher.BlockSize = blockSize;
  59. cipher.FeedbackSize = feedbackSize;
  60. return cipher;
  61. }
  62. }
  63. }