Today we will talk about how to use BCrypt with ASP.NET MVC 3 and C#. First, 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?:

<p>(Use the correct password) Is the password correct?: @ViewBag.HashedPasswordC

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.