using System.Security.Cryptography;
public class EncryptionValue
public int PassIterations { get; set; }
public int KeySize { get; set; }
public string InitVector { get; set; }
public string SaltValue { get; set; }
static HashAlgorithmName hash = HashAlgorithmName.SHA256;
public static string Decrypt(string data, EncryptionValue eV, string passPhrase)
byte[] bytes = Encoding.ASCII.GetBytes(eV.InitVector);
byte[] rgbSalt = Encoding.ASCII.GetBytes(eV.SaltValue);
byte[] buffer = Convert.FromBase64String(data);
byte[] rgbKey = new Rfc2898DeriveBytes(passPhrase, rgbSalt, eV.PassIterations, hash).GetBytes(eV.KeySize / 8);
var managed = Aes.Create("AesManaged");
managed.Padding = PaddingMode.PKCS7;
managed.Mode = CipherMode.CBC;
ICryptoTransform transform = managed.CreateDecryptor(rgbKey, bytes);
MemoryStream stream = new(buffer);
CryptoStream stream2 = new(stream, transform, CryptoStreamMode.Read);
byte[] buffer5 = new byte[buffer.Length];
Console.WriteLine($"buffer5.Length = {buffer5.Length}");
int count = stream2.Read(buffer5, 0, buffer5.Length);
Console.WriteLine($"count = {count}");
return Encoding.UTF8.GetString(buffer5, 0, count);
public static string Encrypt(string data, EncryptionValue eV, string passPhrase)
byte[] bytes = Encoding.ASCII.GetBytes(eV.InitVector);
byte[] rgbSalt = Encoding.ASCII.GetBytes(eV.SaltValue);
byte[] buffer = Encoding.UTF8.GetBytes(data);
byte[] rgbKey = new Rfc2898DeriveBytes(passPhrase, rgbSalt, eV.PassIterations, hash).GetBytes(eV.KeySize / 8);
var managed = Aes.Create("AesManaged");
managed.Padding = PaddingMode.PKCS7;
managed.Mode = CipherMode.CBC;
ICryptoTransform transform = managed.CreateEncryptor(rgbKey, bytes);
MemoryStream stream = new();
CryptoStream stream2 = new(stream, transform, CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
byte[] inArray = stream.ToArray();
return Convert.ToBase64String(inArray);
public static void Main()
var ev = new EncryptionValue
InitVector = "~1B2c3D4e5F6g7H8",
SaltValue = "SnafuFoobar",
var plainText = "Hello world! Mouser trousers are cute. Singer songer singalong. What should i write, what can i write? About the weather? Boring. What i write is boring.";
var enc = Encrypt(plainText, ev, "foobar");
var decrypted = Decrypt(enc, ev, "foobar");