1. static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
  2. {
  3. // Check arguments.
  4. if (plainText == null || plainText.Length <= 0)
  5. throw new ArgumentNullException("plainText");
  6. if (Key == null || Key.Length <= 0)
  7. throw new ArgumentNullException("Key");
  8. if (IV == null || IV.Length <= 0)
  9. throw new ArgumentNullException("Key");
  10. byte[] encrypted;
  11. // Create an AesManaged object
  12. // with the specified key and IV.
  13. using (AesManaged aesAlg = new AesManaged())
  14. {
  15. aesAlg.Key = Key;
  16. aesAlg.IV = IV;
  17. aesAlg.Mode = CipherMode.CBC;
  18. // Create a decrytor to perform the stream transform.
  19. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  20. // Create the streams used for encryption.
  21. using (MemoryStream msEncrypt = new MemoryStream())
  22. {
  23. using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  24. {
  25. using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  26. {
  27. //Write all data to the stream.
  28. swEncrypt.Write(plainText);
  29. }
  30. encrypted = msEncrypt.ToArray();
  31. }
  32. }
  33. }
  34. // Return the encrypted bytes from the memory stream.
  35. return encrypted;
  36. }
  37. static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
  38. {
  39. // Check arguments.
  40. if (cipherText == null || cipherText.Length <= 0)
  41. throw new ArgumentNullException("cipherText");
  42. if (Key == null || Key.Length <= 0)
  43. throw new ArgumentNullException("Key");
  44. if (IV == null || IV.Length <= 0)
  45. throw new ArgumentNullException("Key");
  46. // Declare the string used to hold
  47. // the decrypted text.
  48. string plaintext = null;
  49. // Create an AesManaged object
  50. // with the specified key and IV.
  51. using (AesManaged aesAlg = new AesManaged())
  52. {
  53. aesAlg.Key = Key;
  54. aesAlg.IV = IV;
  55. aesAlg.Mode = CipherMode.CBC;
  56. // Create a decrytor to perform the stream transform.
  57. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  58. // Create the streams used for decryption.
  59. using (MemoryStream msDecrypt = new MemoryStream(cipherText))
  60. {
  61. using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  62. {
  63. using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  64. {
  65. // Read the decrypted bytes from the decrypting stream
  66. // and place them in a string.
  67. plaintext = srDecrypt.ReadToEnd();
  68. }
  69. }
  70. }
  71. }
  72. return plaintext;
  73. }
Comments powered by Disqus