Wednesday, October 8, 2014

BCrypt Primer

Good thing I saw this Postgresql bcrypt use on stackoverflow first..
do
$$
declare hashed text;
begin
    // hashed is what is stored in database
    hashed := crypt('passwordToTest', gen_salt('bf'));

    // then check user login password against the saved hash
    if hashed = crypt('passwordToTest', hashed) then
        raise notice 'matches';
    else
        raise notice 'didn''t match';
    end if;
end;
$$ language 'plpgsql';



..before this BCrypt example for .NET from codeproject:

string myPassword = "passwordToTest";
string mySalt = BCrypt.GenerateSalt();
//mySalt == "$2a$10$rBV2JDeWW3.vKyeQcM8fFO"
string myHash = BCrypt.HashPassword(myPassword, mySalt);
//myHash == "$2a$10$rBV2JDeWW3.vKyeQcM8fFO4777l4bVeQgDL6VIkxqlzQ7TCalQvla"
bool doesPasswordMatch = BCrypt.CheckPassword(myPassword, myHash);



Otherwise, I'll think CheckPassword is a magical functionality of bcrypt. On the latest version of BCrypt.NET from Nuget, the CheckPassword functionality is missing. Seeing how bcrypt hashing and checking works (via PostgreSQL example), CheckPassword is just a simple code:
[TestClass]
public class TheUnitTest
{
    [TestMethod]
    public void Test_if_password_matched()
    {
        // Arrange
        // hashed is what is stored in database
        string hashed = BCrypt.Net.BCrypt.HashPassword("passwordToTest", BCrypt.Net.BCrypt.GenerateSalt(12));

        // Act
        // then check user login password against the saved hash
        bool matches = hashed == BCrypt.Net.BCrypt.HashPassword("passwordToTest", hashed);

        // Assert
        Assert.IsTrue(matches);
    }
}



Happy Coding!

No comments:

Post a Comment