AES.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Text;
  3. using System.Security.Cryptography;
  4. namespace Alipay.EasySDK.Kernel.Util
  5. {
  6. public class AES
  7. {
  8. /// <summary>
  9. /// 128位全0初始向量
  10. /// </summary>
  11. private static readonly byte[] AES_IV = InitIV(16);
  12. /// <summary>
  13. /// AES加密
  14. /// </summary>
  15. /// <param name="plainText">明文</param>
  16. /// <param name="key">对称密钥</param>
  17. /// <returns>密文</returns>
  18. public static string Encrypt(string plainText, string key)
  19. {
  20. try
  21. {
  22. byte[] keyBytes = Convert.FromBase64String(key);
  23. byte[] plainBytes = AlipayConstants.DEFAULT_CHARSET.GetBytes(plainText); ;
  24. RijndaelManaged rijndatel = new RijndaelManaged
  25. {
  26. Key = keyBytes,
  27. Mode = CipherMode.CBC,
  28. Padding = PaddingMode.PKCS7,
  29. IV = AES_IV
  30. };
  31. ICryptoTransform transform = rijndatel.CreateEncryptor(rijndatel.Key, rijndatel.IV);
  32. byte[] cipherBytes = transform.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
  33. return Convert.ToBase64String(cipherBytes);
  34. }
  35. catch (Exception e)
  36. {
  37. throw new Exception("AES加密失败,plainText=" + plainText +
  38. ",keySize=" + key.Length + "。" + e.Message, e);
  39. }
  40. }
  41. /// <summary>
  42. /// AES解密
  43. /// </summary>
  44. /// <param name="cipherText">密文</param>
  45. /// <param name="key">对称密钥</param>
  46. /// <returns>明文</returns>
  47. public static string Decrypt(string cipherText, string key)
  48. {
  49. try
  50. {
  51. byte[] keyBytes = Convert.FromBase64String(key);
  52. byte[] cipherBytes = Convert.FromBase64String(cipherText);
  53. RijndaelManaged rijndatel = new RijndaelManaged
  54. {
  55. Key = keyBytes,
  56. Mode = CipherMode.CBC,
  57. Padding = PaddingMode.PKCS7,
  58. IV = AES_IV
  59. };
  60. ICryptoTransform transform = rijndatel.CreateDecryptor(rijndatel.Key, rijndatel.IV);
  61. byte[] plainBytes = transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
  62. return AlipayConstants.DEFAULT_CHARSET.GetString(plainBytes);
  63. }
  64. catch (Exception e)
  65. {
  66. throw new Exception("AES解密失败,ciphertext=" + cipherText +
  67. ",keySize=" + key.Length + "。" + e.Message, e);
  68. }
  69. }
  70. private static byte[] InitIV(int blockSize)
  71. {
  72. byte[] iv = new byte[blockSize];
  73. for (int i = 0; i < blockSize; ++i)
  74. {
  75. iv[i] = 0x0;
  76. }
  77. return iv;
  78. }
  79. }
  80. }