| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- using Newtonsoft.Json;
- using System;
- using System.IO;
- using System.Security.Cryptography;
- namespace SWRIS.Extensions
- {
- public static class JsonCryptoHelper
- {
- public static void EncryptToFile<T>(T data, string filePath, string key, string iv)
- {
- // 序列化为 JSON 字符串
- string json = JsonConvert.SerializeObject(data, Formatting.None);
- // 加密 JSON 字符串
- byte[] encrypted = EncryptStringToBytes(json, key, iv);
- // 写入文件
- File.WriteAllBytes(filePath, encrypted);
- }
- public static T DecryptFromFile<T>(string filePath, string key, string iv)
- {
- // 读取加密文件
- byte[] encrypted = File.ReadAllBytes(filePath);
- // 解密字节数组
- string json = DecryptStringFromBytes(encrypted, key, iv);
- // 反序列化为对象
- return JsonConvert.DeserializeObject<T>(json);
- }
- private static byte[] EncryptStringToBytes(string plainText, string key, string iv)
- {
- byte[] keyBytes = Convert.FromBase64String(key);
- byte[] ivBytes = Convert.FromBase64String(iv);
- byte[] encrypted;
- using (Aes aes = Aes.Create())
- {
- aes.Key = keyBytes;
- aes.IV = ivBytes;
- ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
- using (MemoryStream ms = new MemoryStream())
- {
- using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
- {
- using (StreamWriter sw = new StreamWriter(cs))
- {
- sw.Write(plainText);
- }
- encrypted = ms.ToArray();
- }
- }
- }
- return encrypted;
- }
- private static string DecryptStringFromBytes(byte[] cipherText, string key, string iv)
- {
- byte[] keyBytes = Convert.FromBase64String(key);
- byte[] ivBytes = Convert.FromBase64String(iv);
- string plaintext;
- using (Aes aes = Aes.Create())
- {
- aes.Key = keyBytes;
- aes.IV = ivBytes;
- ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
- using (MemoryStream ms = new MemoryStream(cipherText))
- {
- using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
- {
- using (StreamReader sr = new StreamReader(cs))
- {
- plaintext = sr.ReadToEnd();
- }
- }
- }
- }
- return plaintext;
- }
- }
- }
|