Created
January 13, 2011 16:14
-
-
Save carlhoerberg/778111 to your computer and use it in GitHub Desktop.
Make the encryption explicit in the domain model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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