JsonCryptoHelper.cs 2.9 KB

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