Here I made a simple self-contained program.cs example on how to encrypt and decrypt data:
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text.Json;
var fileName = "testfile.txt";
if(!File.Exists(fileName)) {
File.WriteAllText(fileName, "Hello World!");
}
// generate random key and iv
var key = new byte[32];
var iv = new byte[16];
using (var rng = RandomNumberGenerator.Create()) {
rng.GetBytes(key);
rng.GetBytes(iv);
}
var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
var data = File.ReadAllBytes(fileName);
// Save
using (FileStream fs = new FileStream(fileName + ".encrypted", FileMode.Create)) {
using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write)) {
await cs.WriteAsync(data, 0, data.Length);
}
}
// Load
using (FileStream fs = new FileStream(fileName + ".encrypted", FileMode.Open)) {
using (CryptoStream cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read)) {
// get data from encrypted file and write a new file
using (FileStream fs2 = new FileStream(fileName + ".decrypted", FileMode.Create)) {
await cs.CopyToAsync(fs2);
}
}
}
You can use any other algorithm instead, as long as it can return an ICrytoTransform
, like the aes.CreateEncryptor()
method (which is inherited from SymmetricAlgorithm
)
Also, I am editing this in 2023 (originally posted in 2017) and I would strongly recommend using JSON serialization instead of BinaryFormatter