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.

90 lines
2.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Apewer.Internals
  6. {
  7. internal class Aes256Helper
  8. {
  9. private static byte[] Fill(byte[] argBytes)
  10. {
  11. const int MaxLength = 32;
  12. var result = new byte[MaxLength];
  13. if ((argBytes == null) || (argBytes.Length == 0))
  14. {
  15. for (int i = 0; i < MaxLength; i++) result[i] = 0;
  16. return result;
  17. }
  18. else
  19. {
  20. var rl = 0;
  21. while (true)
  22. {
  23. for (int i = 0; i < argBytes.Length; i++)
  24. {
  25. if (rl >= MaxLength) return result;
  26. result[rl] = argBytes[i];
  27. rl += 1;
  28. }
  29. }
  30. }
  31. }
  32. private static RijndaelManaged Provider(byte[] argKey)
  33. {
  34. var key = argKey ?? Constant.EmptyBytes; // AesFill(argKey);
  35. var p = new RijndaelManaged();
  36. p.Key = key;
  37. p.Mode = CipherMode.ECB;
  38. p.Padding = PaddingMode.PKCS7;
  39. return p;
  40. }
  41. public static byte[] Encrypt(byte[] argData)
  42. {
  43. return Encrypt(argData, null);
  44. }
  45. /// <summary>对数据进行 AES 加密。</summary>
  46. public static byte[] Encrypt(byte[] argPlain, byte[] argKey = null)
  47. {
  48. if (argPlain == null) return Constant.EmptyBytes;
  49. if (argPlain.Length == 0) return Constant.EmptyBytes;
  50. var rm = Provider(argKey);
  51. var result = new byte[0];
  52. var ct = rm.CreateEncryptor();
  53. try
  54. {
  55. result = ct.TransformFinalBlock(argPlain, 0, argPlain.Length);
  56. }
  57. catch { }
  58. return result;
  59. }
  60. public static byte[] Decrypt(byte[] argData)
  61. {
  62. return Decrypt(argData, null);
  63. }
  64. public static byte[] Decrypt(byte[] argCipher, byte[] argKey)
  65. {
  66. if (argCipher == null) return Constant.EmptyBytes;
  67. if (argCipher.Length == 0) return Constant.EmptyBytes;
  68. var rm = Provider(argKey);
  69. var result = new byte[0];
  70. var ct = rm.CreateDecryptor();
  71. try
  72. {
  73. result = ct.TransformFinalBlock(argCipher, 0, argCipher.Length);
  74. }
  75. catch { }
  76. ct.Dispose();
  77. return result;
  78. }
  79. }
  80. }