Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cangencer
Created February 15, 2012 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cangencer/1833986 to your computer and use it in GitHub Desktop.
Save cangencer/1833986 to your computer and use it in GitHub Desktop.
C# aes encrypt/decrypt
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());
}
}
@beqwulf
Copy link

beqwulf commented Jul 27, 2015

Thanks.

@StefanCiobanu1989
Copy link

Thank you as well!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment