Encrypter.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Island.StandardLib.Storage.Encryption
  6. {
  7. public abstract class EncrypterBase
  8. {
  9. public string DefaultKey;
  10. public EncrypterBase(string defaultKey) => DefaultKey = defaultKey;
  11. public byte[] Encrypt(byte[] plainData) => Encrypt(plainData, DefaultKey);
  12. public byte[] Decrypt(byte[] encryptedData) => Decrypt(encryptedData, DefaultKey);
  13. public abstract byte[] Encrypt(byte[] plainData, string key);
  14. public abstract byte[] Decrypt(byte[] encryptedData, string key);
  15. }
  16. public class RijndaelEncrypter : EncrypterBase
  17. {
  18. public RijndaelEncrypter(string defaultKey) : base(defaultKey) { }
  19. public override byte[] Decrypt(byte[] encryptedData, string key)
  20. {
  21. byte[] bKey = new byte[32];
  22. Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
  23. MemoryStream mStream = new MemoryStream(encryptedData);
  24. RijndaelManaged aes = new RijndaelManaged();
  25. aes.Mode = CipherMode.ECB;
  26. aes.Padding = PaddingMode.PKCS7;
  27. aes.KeySize = 128;
  28. aes.Key = bKey;
  29. CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
  30. try
  31. {
  32. byte[] tmp = new byte[encryptedData.Length + 32];
  33. int len = cryptoStream.Read(tmp, 0, encryptedData.Length + 32);
  34. byte[] ret = new byte[len];
  35. Array.Copy(tmp, 0, ret, 0, len);
  36. return ret;
  37. }
  38. finally
  39. {
  40. cryptoStream.Close();
  41. mStream.Close();
  42. aes.Clear();
  43. }
  44. }
  45. public override byte[] Encrypt(byte[] plainData, string key)
  46. {
  47. MemoryStream mStream = new MemoryStream();
  48. RijndaelManaged aes = new RijndaelManaged();
  49. byte[] bKey = new byte[32];
  50. Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);
  51. aes.Mode = CipherMode.ECB;
  52. aes.Padding = PaddingMode.PKCS7;
  53. aes.KeySize = 128;
  54. aes.Key = bKey;
  55. CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
  56. try
  57. {
  58. cryptoStream.Write(plainData, 0, plainData.Length);
  59. cryptoStream.FlushFinalBlock();
  60. return mStream.ToArray();
  61. }
  62. finally
  63. {
  64. cryptoStream.Close();
  65. mStream.Close();
  66. aes.Clear();
  67. }
  68. }
  69. }
  70. }