C#: Handy BCrypt class for hashing passwords

I was working on an application where I needed to store user names and passwords in a database, as we often do. As we all (should) know we never (ever, ever) store passwords in plain text. If we do, we are setting ourselves up for big trouble if the database contents leaks out or someone hacks their way into it. So what should you do?

You should salt the passwords and you should hash them, and hash them good.

Using raw hash functions to authenticate passwords is as naive as using unsalted hash functions. Don’t. – Thomas Ptacek

So, I was looking for a good implementation of a good hashing algorithm and found one written by Derek Slager called BCrypt.net. I really like it. It has a very clean interface and is super easy to use. So to make sure I don’t lose it (if he would remove it or I would lose the link or something), I post it here. And if it helps someone else to discover it and to ease their day a little, that would be awesome too πŸ™‚

You use it like this:

// Pass a logRounds parameter to GenerateSalt to explicitly specify the
// amount of resources required to check the password. The work factor
// increases exponentially, so each increment is twice as much work. If
// omitted, a default of 10 is used.
string hashed = BCrypt.HashPassword(password, BCrypt.GenerateSalt(12));

// Check the password.
bool matches = BCrypt.CheckPassword(candidate, hashed);

You find the class here.

  • Sheri

    I use same as you. The problem is I have to use it in two difference places. One for Admin and one for user if user would like to change his password.

    I use same method but the generated hashcode differs from each other in this two application.

    What can the problem be?


    • Not sure what you mean here. Differs how? When? Do you have some code example on how you use it?

  • tiago pereira

    how to retrieve hashed password from database?

    • Off topic of this post, sorry. But Google is your friend in this case, and StackOverflow.com is helpful if you run into problems. Good luck πŸ™‚

      • tiago pereira

        google don’t found any thing! only show how to has using bcrypt

      • tiago pereira

        fbcmd.Connection = fbconn;
        fbcmd.CommandText = “SELECT usuario,senha FROM login WHERE usuario = @user”;
        fbcmd.CommandType = CommandType.Text;
        fbcmd.Parameters.Add(“@user”, FbDbType.VarChar).Value = txUsuario.Text;
        fbdr = fbcmd.ExecuteReader();
        i’ve use firebird! this is my query for login! how to retrieve password from database?

        • Ask on stackoverflow. This isn’t the topic of this post, and i can’t help you any further.