Encrypt/decrypt JSON serialized data

c#chris

Active member
Joined
Dec 10, 2024
Messages
25
Programming Experience
1-3
Hello,
is there an easy way to encrypt JSON as follows ?

Writing: Object -> Serialize2JSOM -> Encrypt -> Save2File
Reading: ReadFromFile -> Decrypt -> DeserializeFromJSOM -> Object
 
When you serialize, you can serialize to a stream instead of directory to the file. The stream can be encrypted using AES. On the way back in you decrypt the stream and then give that stream to the deserializer.

 
Yes, there is a relatively easy way to encrypt JSON data in C#. You can utilize libraries such as Newtonsoft.Json for serialization and deserialization, and System.Security.Cryptography for encryption and decryption. Below is a simple implementation that demonstrates the process:
Saving an Object as Encrypted JSON:
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();
            }
        }
    }
}
 
Why serialize the object to a string and then write the string encrypted? Why not serialize the object directory into the crypto stream?
 
Back
Top Bottom