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.

91 lines
3.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 Aes128Helper
  8. {
  9. private static RijndaelManaged Provider(byte[] argkey, byte[] argvector)
  10. {
  11. var vkey = argkey;
  12. if (vkey == null) vkey = new byte[0];
  13. if (vkey.Length != 16) vkey = HashHelper.MD5(vkey);
  14. var viv = argvector;
  15. if (viv == null) viv = new byte[0];
  16. if (viv.Length != 16) viv = HashHelper.MD5(viv);
  17. //vkey = Aes256Fill(argkey);
  18. //viv = Aes256Fill(argvector);
  19. var vp = new RijndaelManaged();
  20. vp.Key = vkey;
  21. vp.IV = viv;
  22. vp.Mode = CipherMode.CBC;
  23. vp.Padding = PaddingMode.PKCS7;
  24. return vp;
  25. }
  26. /// <summary>对数据进行 AES-128 加密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  27. private static byte[] Encrypt(byte[] argData)
  28. {
  29. return Encrypt(argData, null, null);
  30. }
  31. /// <summary>对数据进行 AES-128 加密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  32. private static byte[] Encrypt(byte[] argData, byte[] argKey)
  33. {
  34. return Encrypt(argData, argKey, null);
  35. }
  36. /// <summary>对数据进行 AES-128 加密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  37. private static byte[] Encrypt(byte[] argData, byte[] argKey, byte[] argVector)
  38. {
  39. if (argData == null) return argData;
  40. if (argData.Length == 0) return argData;
  41. var vresult = Constant.EmptyBytes;
  42. var vencryptor = Provider(argKey, argVector).CreateEncryptor();
  43. try
  44. {
  45. vresult = vencryptor.TransformFinalBlock(argData, 0, argData.Length);
  46. }
  47. catch { }
  48. vencryptor.Dispose();
  49. return vresult;
  50. }
  51. /// <summary>对数据进行 AES-128 解密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  52. private static byte[] Decrypt(byte[] argdata)
  53. {
  54. return Decrypt(argdata, null, null);
  55. }
  56. /// <summary>对数据进行 AES-128 解密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  57. private static byte[] Decrypt(byte[] argdata, byte[] argkey)
  58. {
  59. return Decrypt(argdata, argkey, null);
  60. }
  61. /// <summary>对数据进行 AES-128 解密。<para>若密钥不为 128 位则以密钥 MD5 作为密钥。若向量不为 128 位则与密钥相同。</para></summary>
  62. private static byte[] Decrypt(byte[] argdata, byte[] argkey, byte[] argvector)
  63. {
  64. if (argdata == null) return argdata;
  65. if (argdata.Length == 0) return argdata;
  66. var vresult = Constant.EmptyBytes;
  67. var vdecryptor = Provider(argkey, argvector).CreateDecryptor();
  68. try
  69. {
  70. vresult = vdecryptor.TransformFinalBlock(argdata, 0, argdata.Length);
  71. }
  72. catch { }
  73. vdecryptor.Dispose();
  74. return vresult;
  75. }
  76. }
  77. }