I was just reading today about yet another site that stored their user’s passwords in plain text. Of course the issue is if you get hacked you expose everyone’s passwords to the world, passwords they might be using on other sites, etc. There is a lot of debate of how you should go about encrypting/hashing/obscuring passwords and with a little research I found a lot of people seem to think BCrypt is the way to go. Check out this article.

I won’t debate on what you should use for your website, you need to make that decision. I played with a
BCrypt C# library I found on Google Code. Today I’ll build a simple ASP.NET MVC 3 app that will use it to show how easy it is to work with in a project.

Open up Visual Studio 2010 and make sure you have the
ASP.NET MVC 3 package installed. Create a new project: File -> New Project -> ASP.NET MVC 3 Web Application and call it MvcBCrypt. For the project template select Empty. Make sure for the View Engine you pick Razor.



Right-click on the Controllers folder and select Add -> Controller

Name the new Controller HomeController.



When the code shows up right-click on the Index() and choose Add View. Use the default settings (see below) and then click Add.



Modify the code in the Index.cshtml file to look like this:

@{
    ViewBag.Title = "Home Page";
}   

<p>Password: @ViewBag.Password</p>
<p>Hashed Password: @ViewBag.HashedPassword</p>
<p>(Use a wrong password) Is the password correct?: @ViewBag.HashedPasswordChecked1</p>
<p>(Use the correct password) Is the password correct?: @ViewBag.HashedPasswordChecked2

Its time to bring in the
BCrypt code now. Go to this link and copy the source code. Create a new folder in your project called Utility and create a new class file in there called BCrypt.cs.



Note: Yes, there are better places to put this new BCrypt class file but for simplicity its just going to live in a Utility folder for this demonstration.

Make sure to paste in the code and save the file. When you do this make sure to fix the namespace and remove the following:

[assembly: System.Reflection.AssemblyVersion("0.3")]

Go back to the HomeController file and modify it like so:

using MvcBCrypt.Utility;

Add the new code to test out the BCrypt class:

public ActionResult Index()
{
    string password = "myPassword1";
    string wrongPassword = "wrongPasswOrd1";   

    string hashedPassword = BCrypt.HashPassword(password, BCrypt.GenerateSalt(12));
    bool doesItMatch1 = BCrypt.CheckPassword(wrongPassword, hashedPassword);
    bool doesItMatch2 = BCrypt.CheckPassword(password, hashedPassword);   

    ViewBag.Password = password;
    ViewBag.HashedPassword = hashedPassword;
    ViewBag.HashedPasswordChecked1 = doesItMatch1;
    ViewBag.HashedPasswordChecked2 = doesItMatch2;   

    return View();
}

Save and run the project.



Note: Using the new Library Package Manager I did see another BCrypt library out there so you might want to experiment with that one as well.