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.

89 lines
2.6 KiB

  1. using System.IO;
  2. using System.Security.Cryptography;
  3. namespace Apewer.Internals
  4. {
  5. class DesHelper
  6. {
  7. private static byte[] Fill(byte[] argbytes)
  8. {
  9. const int MaxLength = 8;
  10. var vresult = new byte[MaxLength];
  11. if ((argbytes == null) || (argbytes.Length == 0))
  12. {
  13. for (int i = 0; i < MaxLength; i++) vresult[i] = 0;
  14. return vresult;
  15. }
  16. else
  17. {
  18. var vrl = 0;
  19. while (true)
  20. {
  21. for (int i = 0; i < argbytes.Length; i++)
  22. {
  23. if (vrl >= MaxLength) return vresult;
  24. vresult[vrl] = argbytes[i];
  25. vrl += 1;
  26. }
  27. }
  28. }
  29. }
  30. private static DESCryptoServiceProvider Provider(byte[] argkey, byte[] argvector)
  31. {
  32. var vkey = Fill(argkey);
  33. var viv = Fill(argvector);
  34. var vcsp = new DESCryptoServiceProvider();
  35. vcsp.Key = vkey;
  36. vcsp.IV = viv;
  37. return vcsp;
  38. }
  39. /// <summary>对数据进行 DES 加密。</summary>
  40. private static byte[] Encrypt(byte[] argdata, byte[] argkey, byte[] argvector)
  41. {
  42. if ((argdata == null) || (argdata.Length == 0)) return argdata;
  43. var vresult = Constant.EmptyBytes;
  44. var vms = new MemoryStream();
  45. var vcs = new CryptoStream(vms, Provider(argkey, argvector).CreateEncryptor(), CryptoStreamMode.Write);
  46. //try
  47. {
  48. vcs.Write(argdata, 0, argdata.Length);
  49. vcs.FlushFinalBlock();
  50. vresult = vms.ToArray();
  51. }
  52. //finally { }
  53. vcs.Dispose();
  54. vms.Dispose();
  55. return vresult;
  56. }
  57. /// <summary>对数据进行 DES 解密。</summary>
  58. private static byte[] Decrypt(byte[] argdata, byte[] argkey, byte[] argvector)
  59. {
  60. if ((argdata == null) || (argdata.Length == 0)) return argdata;
  61. var vresult =Constant. EmptyBytes;
  62. var vms = new MemoryStream();
  63. var vcs = new CryptoStream(vms, Provider(argkey, argvector).CreateDecryptor(), CryptoStreamMode.Write);
  64. //try
  65. {
  66. vcs.Write(argdata, 0, argdata.Length);
  67. vcs.FlushFinalBlock();
  68. vresult = vms.ToArray();
  69. }
  70. //finally { }
  71. vcs.Dispose();
  72. vms.Dispose();
  73. return vresult;
  74. }
  75. }
  76. }