Skip to content

Instantly share code, notes, and snippets.

@carlhoerberg
Created January 13, 2011 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlhoerberg/778111 to your computer and use it in GitHub Desktop.
Save carlhoerberg/778111 to your computer and use it in GitHub Desktop.
Make the encryption explicit in the domain model
public class EncryptedColumnInEntity : Entity
{
protected virtual byte[] EncryptedText { get; set; }
/// <summary>
/// Decryptes the text stored in the database
/// </summary>
/// <exception cref="CryptographicException">Throws CryptographicException when the password isn't valid</exception>
/// <param name="password">The password which the text was encrypted with</param>
/// <returns>Decrypted text</returns>
public virtual string GetText(string password)
{
var salt = EncryptedText.Take(16).ToArray();
using (var aes = new AesManaged())
using (var byteDeriver = new Rfc2898DeriveBytes(password, salt))
using (var decryptor = aes.CreateDecryptor(byteDeriver.GetBytes(32), byteDeriver.GetBytes(16)))
{
var decryptedBytes = decryptor.TransformFinalBlock(EncryptedText, 16, EncryptedText.Length - 16);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
public virtual void SetText(string password, string inputText)
{
using (var aes = new AesManaged())
using (var byteDeriver = new Rfc2898DeriveBytes(password, 16))
using (var encryptor = aes.CreateEncryptor(byteDeriver.GetBytes(32), byteDeriver.GetBytes(16)))
{
var textBytes = Encoding.UTF8.GetBytes(inputText);
var encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
EncryptedText = byteDeriver.Salt.Concat(encryptedBytes).ToArray();
}
}
public virtual void ChangePassword(string oldpassword, string newpassword)
{
SetText(newpassword, GetText(oldpassword));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment