Secure.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Quadarax.Foundation.Common.Security
  6. {
  7. public static class Secure
  8. {
  9. static string _passwordHash = "OmMC:7i%+o.MlIeg`kRcv:R3haPyx|#vuM,G,oB1n=IBUG'!M6";
  10. static string _saltKey = "vo:Y:pWYcS\"*m@^6R\\O#$eSg!,23H\\R8KfIi\\u1IED91TE0J#~";
  11. static string _vIKey = "@!PYn,b=t4\\%`Am`z!ubwE1H2Ek1?*R&,6cF:f1mZJ1dxB&DZH";
  12. public static void SetProperties(string passwordHash, string saltKey, string vIKey)
  13. {
  14. _passwordHash = passwordHash;
  15. _saltKey = saltKey;
  16. _vIKey = vIKey;
  17. }
  18. public static string Encrypt(string plainText)
  19. {
  20. var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
  21. var keyBytes = new Rfc2898DeriveBytes(_passwordHash, Encoding.ASCII.GetBytes(_saltKey)).GetBytes(256 / 8);
  22. var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
  23. var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(_vIKey));
  24. byte[] cipherTextBytes;
  25. using (var memoryStream = new MemoryStream())
  26. {
  27. using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
  28. {
  29. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  30. cryptoStream.FlushFinalBlock();
  31. cipherTextBytes = memoryStream.ToArray();
  32. cryptoStream.Close();
  33. }
  34. memoryStream.Close();
  35. }
  36. return Convert.ToBase64String(cipherTextBytes);
  37. }
  38. public static string Decrypt(string encryptedText)
  39. {
  40. var cipherTextBytes = Convert.FromBase64String(encryptedText);
  41. var keyBytes = new Rfc2898DeriveBytes(_passwordHash, Encoding.ASCII.GetBytes(_saltKey)).GetBytes(256 / 8);
  42. var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
  43. var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(_vIKey));
  44. var memoryStream = new MemoryStream(cipherTextBytes);
  45. var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
  46. byte[] plainTextBytes = new byte[cipherTextBytes.Length];
  47. int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
  48. memoryStream.Close();
  49. cryptoStream.Close();
  50. return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
  51. }
  52. }
  53. }