Skip to content

Instantly share code, notes, and snippets.

@jkuemerle
Last active December 28, 2015 16:59
Show Gist options
  • Select an option

  • Save jkuemerle/7532705 to your computer and use it in GitHub Desktop.

Select an option

Save jkuemerle/7532705 to your computer and use it in GitHub Desktop.
Method to encrypt data and optionally HMAC it.
public string Encrypt(string Data, string KeyName, Func<string> IntegrityFunction)
{
if (null != IntegrityFunction)
Data = AddHMAC(Data, IntegrityFunction);
var val = System.Text.UnicodeEncoding.Unicode.GetBytes(Data);
using (var crypter = new System.Security.Cryptography.RijndaelManaged())
{
var iv = new byte[crypter.BlockSize / 8].FillWithEntropy();
KeyInfo key = GetKeyInfo(KeyName, iv, crypter);
byte[] encrypted;
crypter.IV = iv;
crypter.Key = key.KeyBytes;
crypter.Mode = CipherMode.CBC;
using (var encrypter = crypter.CreateEncryptor())
{
using (var to = new MemoryStream())
{
using (var writer = new CryptoStream(to, encrypter, CryptoStreamMode.Write))
{
writer.Write(val, 0, val.Length);
writer.FlushFinalBlock();
encrypted = to.ToArray();
}
}
}
return string.Format("{0}\0{1}\0{2}", Convert.ToBase64String(iv), Convert.ToBase64String(encrypted), ComputeHMAC(encrypted,key.SecretBytes));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment