AESHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace TEAMModelOS.Controllers.Third.Helpers
  8. {
  9. public class AESHelper
  10. {
  11. /// <summary>
  12. /// 有密码的加密
  13. /// </summary>
  14. /// <param name="toEncrypt">加密字符</param>
  15. /// <param name="key">加密的密码</param>
  16. /// <returns></returns>
  17. public static string AESEncrypt(string toEncrypt, string key)
  18. {
  19. byte[] keyArray = hexStringTobyte(key);
  20. byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
  21. RijndaelManaged rDel = new RijndaelManaged();
  22. rDel.KeySize = 128;
  23. rDel.BlockSize = 128;
  24. rDel.Key = keyArray;
  25. rDel.Mode = CipherMode.ECB;
  26. rDel.Padding = PaddingMode.PKCS7;
  27. ICryptoTransform cTransform = rDel.CreateEncryptor();
  28. byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  29. return byteToHexString(resultArray);
  30. }
  31. /// <summary>
  32. /// 解密
  33. /// </summary>
  34. /// <param name="toDecrypt">解密字符</param>
  35. /// <param name="key">加密的密码</param>
  36. /// <returns></returns>
  37. public static string AESDecrypt(string toDecrypt, string key)
  38. {
  39. byte[] keyArray = hexStringTobyte(key);
  40. byte[] dest = hexStringTobyte(toDecrypt);
  41. RijndaelManaged rDel = new RijndaelManaged();
  42. rDel.KeySize = 128;
  43. rDel.BlockSize = 128;
  44. rDel.Key = keyArray;
  45. rDel.Mode = CipherMode.ECB;
  46. rDel.Padding = PaddingMode.PKCS7;
  47. ICryptoTransform cTransform = rDel.CreateDecryptor();
  48. byte[] resultArray = cTransform.TransformFinalBlock(dest, 0, dest.Length);
  49. return UTF8Encoding.UTF8.GetString(resultArray);
  50. }
  51. private static byte[] hexStringTobyte(String s)
  52. {
  53. if (string.IsNullOrEmpty(s)) return null;
  54. s = s.ToLower();
  55. int byteArrayLength = s.Length / 2;
  56. byte[] b = new byte[byteArrayLength];
  57. for (int i = 0; i < byteArrayLength; i++)
  58. {
  59. byte b0 = Convert.ToByte(s.Substring(i * 2, 2), 16);
  60. b[i] = b0;
  61. }
  62. return b;
  63. }
  64. public static string byteToHexString(byte[] t)
  65. {
  66. StringBuilder sb = new StringBuilder();
  67. for (int i = 0; i < t.Length; i++)
  68. {
  69. sb.Append(t[i].ToString("x").PadLeft(2, '0'));
  70. }
  71. return sb.ToString().ToUpper();
  72. }
  73. }
  74. }