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.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 AES
  11. {
  12. public static byte[] Encrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  13. {
  14. using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
  15. {
  16. return Encrypt(cipher, value);
  17. }
  18. }
  19. public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, int keyLength, int blockLength, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  20. {
  21. using (var cipher = CreateCipher(key, iv, keyLength, blockLength, feedbackSize, mode, paddingMode))
  22. {
  23. return Decrypt(cipher, value);
  24. }
  25. }
  26. public static byte[] Encrypt(RijndaelManaged cipher, byte[] value)
  27. {
  28. byte[] encryptedBytes;
  29. using (var encryptor = cipher.CreateEncryptor())
  30. using (MemoryStream ms = new MemoryStream())
  31. using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
  32. using (var bw = new BinaryWriter(cs, Encoding.UTF8))
  33. {
  34. bw.Write(value);
  35. bw.Close();
  36. encryptedBytes = ms.ToArray();
  37. }
  38. return encryptedBytes;
  39. }
  40. public static byte[] Decrypt(RijndaelManaged cipher, byte[] value)
  41. {
  42. byte[] decryptedBytes;
  43. using (var decryptor = cipher.CreateDecryptor())
  44. using (MemoryStream ms = new MemoryStream())
  45. using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
  46. using (var bw = new BinaryWriter(cs, Encoding.UTF8))
  47. {
  48. bw.Write(value);
  49. bw.Close();
  50. decryptedBytes = ms.ToArray();
  51. }
  52. return decryptedBytes;
  53. }
  54. public static RijndaelManaged CreateCipher(byte[] key, byte[] iv, int keyLength, int blockSize, int feedbackSize, CipherMode mode, PaddingMode paddingMode)
  55. {
  56. RijndaelManaged cipher = new RijndaelManaged();
  57. cipher.Mode = mode;
  58. cipher.Padding = paddingMode;
  59. cipher.Key = key;
  60. cipher.IV = iv;
  61. cipher.KeySize = keyLength;
  62. cipher.BlockSize = blockSize;
  63. cipher.FeedbackSize = feedbackSize;
  64. return cipher;
  65. }
  66. }
  67. }