Logo

NHibernate

The object-relational mapper for .NET

Encrypting password (or other strings) in NHibernate

As you can read in every forum the solution to encrypting/decrypting a password is using an IUserType. Implementing an IUserType in NH is somewhat easy, so we added to uNHAddins a user type which will do the encryption.

The source code can be grabbed from uNHAddins trunk.

If you use it “as is” you will get an encryption using the symmetric algorithm DESCryptoServiceProvider. There is no special decision for this but to have some default option to do the job.

There are several ways to use the user type, the most common but less recommended (unless you are using it only once):

<property name="Password" type="uNHAddIns.UserTypes.EncryptedString, uNHAddins" />

The preferred way will be using <typedef> to define the user type as in the following:

<typedef class="uNHAddIns.UserTypes.EncryptedString, uNHAddIns" name="Encrypted">
  <param name="encryptor">uNhAddIns.UserTypes.uNHAddinsEncryptor, uNhAddIns</param>
  <param name="encryptionKey">myRGBKey</param>
</typedef>

The parameters are optional but give you an easy option to extend the user type to use your own algorithm.

The encryptor paramater expects an implementation of IEncryptor, if you don’t set it you get the uNHAddinsEncryptor implementation. Implementing the interface is very easy you just need to say how you encrypt and decrypt and if you want to use an external key set in the typedef parameters then you can get this using the EncryptionKey property.

public interface IEncryptor
{
  string Encrypt(string password);
  string Decrypt(string encryptedPassword);
  string EncryptionKey { get; set; }
}

Using it now in your code is as easy as:

<property name="Password" type="Encrypted" />

The Password property keeps being implemented as a string, so you don’t touch your existing code.


Posted Sat, 21 February 2009 07:18:00 PM by Gustavo
Filed under:

comments powered by Disqus
© NHibernate Community 2024