Skip to content

Instantly share code, notes, and snippets.

@wqweto
Last active October 27, 2022 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wqweto/54e374f04754708d6d715f162c3d9b10 to your computer and use it in GitHub Desktop.
Save wqweto/54e374f04754708d6d715f162c3d9b10 to your computer and use it in GitHub Desktop.
Simple PBKDF2 based AES-256 encryption
public class SimpleAES
{
private const int SALT_SIZE = 8;
private const int KEY_SIZE = 256;
public static string Encrypt(string text, string passphrase)
{
byte[] result = null;
if (Encrypt(Encoding.UTF8.GetBytes(text), passphrase, ref result))
{
return Convert.ToBase64String(result);
}
return null;
}
public static string Decrypt(string encr, string passphrase)
{
byte[] result = null;
if (Decrypt(Convert.FromBase64String(encr), passphrase, ref result))
{
return Encoding.UTF8.GetString(result);
}
return null;
}
public static bool Encrypt(byte[] buffer, string passphrase, ref byte[] result)
{
try
{
var salt = GetRandomBytes(SALT_SIZE);
using (var cipher = GetCipher(passphrase, salt, KEY_SIZE))
using (var ms = new MemoryStream())
using (var trans = cipher.CreateEncryptor(cipher.Key, cipher.IV))
using (var cs = new CryptoStream(ms, trans, CryptoStreamMode.Write))
{
ms.Write(salt, 0, salt.Length);
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
result = ms.ToArray();
return true;
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
return false;
}
public static bool Decrypt(byte[] buffer, string passphrase, ref byte[] result)
{
try
{
var salt = new byte[SALT_SIZE];
Array.Copy(buffer, salt, SALT_SIZE);
using (var cipher = GetCipher(passphrase, salt, KEY_SIZE))
using (var ms = new MemoryStream())
using (var trans = cipher.CreateDecryptor(cipher.Key, cipher.IV))
using (var cs = new CryptoStream(ms, trans, CryptoStreamMode.Write))
{
cs.Write(buffer, SALT_SIZE, buffer.Length - SALT_SIZE);
cs.FlushFinalBlock();
result = ms.ToArray();
return true;
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
return false;
}
private static byte[] GetRandomBytes(int size)
{
var salt = new byte[size];
var rng = new Random();
rng.NextBytes(salt);
return salt;
}
private static Aes GetCipher(string passphrase, byte[] salt, int keysize)
{
var aes = Aes.Create();
aes.KeySize = keysize;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
using (var pbkdf2 = new Rfc2898DeriveBytes(passphrase, salt, 100000))
{
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
}
return aes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment