This is what you would like to do:
OurKey.SetValue("Password", StringEncryptor.EncryptString(textBoxPassword.Text));
OurKey.GetValue("Password", StringEncryptor.DecryptString(textBoxPassword.Text));
You can do that with this the following classes. This class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using Ninject.
public class StringEncryptor
{
private static IKernel _kernel;
static StringEncryptor()
{
_kernel = new StandardKernel(new EncryptionModule());
}
public static string EncryptString(string plainText)
{
return _kernel.Get<IStringEncryptor>().EncryptString(plainText);
}
public static string DecryptString(string encryptedText)
{
return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);
}
}
This next class is the ninject class that allows you to inject the various algorithms:
public class EncryptionModule : StandardModule
{
public override void Load()
{
Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();
}
}
This is the interface that any algorithm needs to implement to encrypt/decrypt strings:
public interface IStringEncryptor
{
string EncryptString(string plainText);
string DecryptString(string encryptedText);
}
This is a implementation using the TripleDES algorithm:
public class TripleDESStringEncryptor : IStringEncryptor
{
private byte[] _key;
private byte[] _iv;
private TripleDESCryptoServiceProvider _provider;
public TripleDESStringEncryptor()
{
_key = System.Text.ASCIIEncoding.ASCII.GetBytes("GSYAHAGCBDUUADIADKOPAAAW");
_iv = System.Text.ASCIIEncoding.ASCII.GetBytes("USAZBGAW");
_provider = new TripleDESCryptoServiceProvider();
}
#region IStringEncryptor Members
public string EncryptString(string plainText)
{
return Transform(plainText, _provider.CreateEncryptor(_key, _iv));
}
public string DecryptString(string encryptedText)
{
return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));
}
#endregion
private string Transform(string text, ICryptoTransform transform)
{
if (text == null)
{
return null;
}
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
byte[] input = Encoding.Default.GetBytes(text);
cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock();
return Encoding.Default.GetString(stream.ToArray());
}
}
}
}
You can watch my video and download the code for this at : http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html