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.

66 lines
2.2 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace GBNewEnergy.Protocol.NEEncrypts
  7. {
  8. public class NEAES128EncryptImpl : INEEncrypt
  9. {
  10. private readonly NEGlobalConfigs _nEConfigs;
  11. /// <summary>
  12. /// 盐字节必须为至少8个字节
  13. /// </summary>
  14. private readonly static byte[] saltBytes = new byte[9] { 13, 34, 27, 67, 189, 255, 104, 219, 122 };
  15. public NEAES128EncryptImpl(NEGlobalConfigs nEConfigs)
  16. {
  17. _nEConfigs = nEConfigs;
  18. }
  19. public byte[] Encrypt(byte[] buffer)
  20. {
  21. using (var ms = new MemoryStream())
  22. {
  23. using (var AES = new RijndaelManaged())
  24. {
  25. AES.KeySize = 256;
  26. AES.BlockSize = 128;
  27. var key = new Rfc2898DeriveBytes(_nEConfigs.NEEncryptKeyBytes, saltBytes, 1000);
  28. AES.Key = key.GetBytes(32);
  29. AES.IV = key.GetBytes(16);
  30. AES.Mode = CipherMode.CBC;
  31. using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
  32. {
  33. cs.Write(buffer, 0, buffer.Length);
  34. cs.Close();
  35. }
  36. return ms.ToArray();
  37. }
  38. }
  39. }
  40. public byte[] Decrypt(byte[] buffer)
  41. {
  42. using (var ms = new MemoryStream())
  43. using (var AES = new RijndaelManaged())
  44. {
  45. AES.KeySize = 256;
  46. AES.BlockSize = 128;
  47. var key = new Rfc2898DeriveBytes(_nEConfigs.NEEncryptKeyBytes, saltBytes, 1000);
  48. AES.Key = key.GetBytes(32);
  49. AES.IV = key.GetBytes(16);
  50. AES.Mode = CipherMode.CBC;
  51. using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
  52. {
  53. cs.Write(buffer, 0, buffer.Length);
  54. cs.Close();
  55. }
  56. return ms.ToArray();
  57. }
  58. }
  59. }
  60. }