C# How to hash a password

Sometimes you have to keep things simple. This will show you, how to hash a password (string) using MD5 or SHA-1 in C#.

First of all, put this in your source:

using System.Web.Security;

Next, create a static method that we can use anywhere in our solution:

public static string HashedPassword(string password)
{
   return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
}

The FormsAuthentication class is the same, as used by the asp.net Login control. Replace md5 with "sha1" if you want a more safer hashing. Sha1 uses a 160-bit hash function which resembles the md5.

All you have to do now, is to use the new method, before saving the password to the database:

UserPassword = HashedPassword(myPasswordField);

UserPassword is the field name in your database and myPasswordField is the field name, containing the password that the user typed, when creating the user.

In your login method, you have to do almost the same. The user is typing a username and password, where the password is typed in clear text. Clear text can't be compared to the password that we've saved in the database, because it was MD5 hashed.

The trick here is to use our static method again:

if (HashedPassword(enteredPassword) == UserPassword)
  // Password was correct
else
  // Password was incorrect

enteredPassword is the field name, containing what ever the user was typing when trying to login. UserPassword is the field name, containg the users password from the database.

Remember

First of all, MD5 hashing is one way only, which means that it's not possible to "De-Hash" it again. Second, MD5 is not the safest way to save passwords in a none-readable way. But sha1 should be useful in most cases.

7. December 2010 21:45 by bbc | Comments (0) | Permalink

About me

Me? My name is Brian and I was born in 1971. I live in Aalborg / Denmark with my family and has worked with IT since 1991, when I finished my education.

 

What do i do? I work as a .NET programmer and that is the perfect world for  me Cool

 

What about hobbies? I have so many different interests, when I don't go to work. I'm chairman of the board in Aalborg Billiard Club, which is one of the largest billiard clubs in Denmark. And then I do a lot photos and love to go around in abandoned places to find interesting things to shoot with my camera.

 

Why English? I decided to write everything in English, even that I'm not perfect to write the language. I hope you can understand my blog entries anyway and don't kill me for all the spelling mistakes... BTW. Comments are disabled because spammers just can't stop :-(