using System.Security.Cryptography;
private static readonly string _key = "~ineedtochangethiskeybeacauseeveryoneknowsit~";
private static readonly string _encrypted= "";
private static readonly string _plaintext= "";
private static readonly byte[] _pepper = new byte[] { 0x04, 0xC5, 0x02, 0xF8, 0xD3, 0xD4, 0x23, 0xB9 };
public static void Main()
Console.WriteLine($"Encrypted: {Encrypt(_plaintext)}");
Console.WriteLine($"Decrypted: {Decrypt(_encrypted)}");
public static string Decrypt(string encryptedText)
if (encryptedText == null) return null;
if (encryptedText == "") return "";
var ivAndCiphertext = Convert.FromBase64String(encryptedText);
if (ivAndCiphertext.Length >= 16)
var ciphertext = new byte[ivAndCiphertext.Length - 16];
Array.Copy(ivAndCiphertext, 0, iv, 0, iv.Length);
Array.Copy(ivAndCiphertext, iv.Length, ciphertext, 0, ciphertext.Length);
using var aes = Aes.Create();
using var pbkdf2 = new Rfc2898DeriveBytes(_key, _pepper, 32767);
var key = pbkdf2.GetBytes(32);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using var aesTransformer = aes.CreateDecryptor();
var plaintext = aesTransformer.TransformFinalBlock(ciphertext, 0, ciphertext.Length);
return Encoding.UTF8.GetString(plaintext);
throw new ArgumentException("Failed to decrypt string, it is not a valid encrypted string.");
public static string Encrypt(string text)
if (text == null) return null;
if (text == "") return "";
using var aes = Aes.Create();
using var pbkdf2 = new Rfc2898DeriveBytes(_key, _pepper, 32767);
using var rng = new RNGCryptoServiceProvider();
var key = pbkdf2.GetBytes(32);
var plaintext = Encoding.UTF8.GetBytes(text);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using var aesTransformer = aes.CreateEncryptor();
var ciphertext = aesTransformer.TransformFinalBlock(plaintext, 0, plaintext.Length);
var ivAndCiphertext = new byte[iv.Length + ciphertext.Length];
Array.Copy(iv, 0, ivAndCiphertext, 0, iv.Length);
Array.Copy(ciphertext, 0, ivAndCiphertext, iv.Length, ciphertext.Length);
return Convert.ToBase64String(ivAndCiphertext);