public
Created

C# aes encrypt/decrypt

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
public const int KEY_SIZE = 16;
 
public byte[] Encrypt (string password, string input)
{
var sha256CryptoServiceProvider = new SHA256CryptoServiceProvider();
var hash = sha256CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(password));
var key = new byte[KEY_SIZE];
var iv = new byte[KEY_SIZE];
 
Buffer.BlockCopy(hash, 0, key, 0, KEY_SIZE);
Buffer.BlockCopy(hash, KEY_SIZE, iv, 0, KEY_SIZE);
 
using (var cipher = new AesCryptoServiceProvider().CreateEncryptor(key, iv))
using (var output = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(output, cipher, CryptoStreamMode.Write))
{
var inputBytes = Encoding.UTF8.GetBytes(input);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
}
return output.ToArray();
}
}
 
public string Decrypt(string password, byte[] encryptedBytes)
{
var sha256CryptoServiceProvider = new SHA256CryptoServiceProvider();
var hash = sha256CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(password));
var key = new byte[KEY_SIZE];
var iv = new byte[KEY_SIZE];
 
Buffer.BlockCopy(hash, 0, key, 0, KEY_SIZE);
Buffer.BlockCopy(hash, KEY_SIZE, iv, 0, KEY_SIZE);
 
using (var cipher = new AesCryptoServiceProvider().CreateDecryptor(key, iv))
using (var source = new MemoryStream(encryptedBytes))
using (var output = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(source, cipher, CryptoStreamMode.Read))
{
cryptoStream.CopyTo(output);
}
return Encoding.UTF8.GetString(output.ToArray());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.