Friday, 7 November 2008

Encrypting Password Fields in C#

This is probably nothing new to many people, but for me it was something new so I’m blogging about it.  There is often the need to encrypt password fields (or any other field for that matter) when storing it in the database.  There are a few ways to do it in the database too, but if you’re using an ORM like LINQ to SQL or NHibernate for .NET then you’ll find that the SQL used to encrypt and decrypt can add un-necessary complexity to your application.  Instead .NET provides you with many means to encrypt and decrypt data using cryptography.

Don’t Decrypt Passwords

The first lesson I’ve learned when dealing with cryptography is that you should never decrypt a password.  If you need to validate a password then you should re-encrypt the password and then validate the two encrypted passwords against each other.

.NET provides encryption by the System.Security.Cryptography namespace and uses the provider model that’s so prominent in .NET.  The different encryption types I won’t go into here, that’s something you’ll have to find out for yourself, however the most popular seems to be MD5 or SHA1.

The code to encrypt a string field is very simple.

MD5CryptoServiceProvider md5crypto = new MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(inputString);
data = md5crypto.ComputeHash(data);
return System.Text.Encoding.ASCII.GetString(data);

Convert the string to a byte array, compute the hash, return the encrypted hash.  This can be used by any type of data that allows conversion into a byte array.

I would highly recommend wrapping up the MD5 encryption in an interface so you can plug in other encryption types that are appropriate for your security concerns.

1 comment:

simi said...


First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook