using Newtonsoft.Json;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class JsonEncryption
{
private static readonly string key = "your-encryption-key"; // Use a secure key
public static void SaveToFile<T>(T obj, string filePath)
{
string json = JsonConvert.SerializeObject(obj);
byte[] encryptedData = EncryptStringToBytes(json, key);
File.WriteAllBytes(filePath, encryptedData);
}
private static byte[] EncryptStringToBytes(string plainText, string key)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.GenerateIV();
using (var ms = new MemoryStream())
{
ms.Write(aes.IV, 0, aes.IV.Length);
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
return ms.ToArray();
}
}
}
}