JsonCryptoHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Security.Cryptography;
  6. namespace SWRIS.Extensions
  7. {
  8. public static class JsonCryptoHelper
  9. {
  10. public static void EncryptToFile<T>(T data, string filePath, string key, string iv)
  11. {
  12. // 序列化为 JSON 字符串
  13. string json = JsonConvert.SerializeObject(data, Formatting.None);
  14. // 加密 JSON 字符串
  15. byte[] encrypted = EncryptStringToBytes(json, key, iv);
  16. // 写入文件
  17. File.WriteAllBytes(filePath, encrypted);
  18. }
  19. public static T DecryptFromFile<T>(string filePath, string key, string iv)
  20. {
  21. // 读取加密文件
  22. byte[] encrypted = File.ReadAllBytes(filePath);
  23. // 解密字节数组
  24. string json = DecryptStringFromBytes(encrypted, key, iv);
  25. // 反序列化为对象
  26. return JsonConvert.DeserializeObject<T>(json);
  27. }
  28. [Obfuscation(Feature = "virtualization", Exclude = false)]
  29. private static byte[] EncryptStringToBytes(string plainText, string key, string iv)
  30. {
  31. byte[] keyBytes = Convert.FromBase64String(key);
  32. byte[] ivBytes = Convert.FromBase64String(iv);
  33. byte[] encrypted;
  34. using (Aes aes = Aes.Create())
  35. {
  36. aes.Key = keyBytes;
  37. aes.IV = ivBytes;
  38. ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
  39. using (MemoryStream ms = new MemoryStream())
  40. {
  41. using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
  42. {
  43. using (StreamWriter sw = new StreamWriter(cs))
  44. {
  45. sw.Write(plainText);
  46. }
  47. encrypted = ms.ToArray();
  48. }
  49. }
  50. }
  51. return encrypted;
  52. }
  53. [Obfuscation(Feature = "virtualization", Exclude = false)]
  54. private static string DecryptStringFromBytes(byte[] cipherText, string key, string iv)
  55. {
  56. byte[] keyBytes = Convert.FromBase64String(key);
  57. byte[] ivBytes = Convert.FromBase64String(iv);
  58. string plaintext;
  59. using (Aes aes = Aes.Create())
  60. {
  61. aes.Key = keyBytes;
  62. aes.IV = ivBytes;
  63. ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
  64. using (MemoryStream ms = new MemoryStream(cipherText))
  65. {
  66. using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
  67. {
  68. using (StreamReader sr = new StreamReader(cs))
  69. {
  70. plaintext = sr.ReadToEnd();
  71. }
  72. }
  73. }
  74. }
  75. return plaintext;
  76. }
  77. }
  78. }