Search code examples
.netsql-serverbcrypt

How to use .Net implementation of BCrypt for SQL Server?


I've searched in google, unfortunately I can't found any expect answers I want.

I've downloaded .NET implementation of BCrypt

Honest, I usually coding in PHP language, i have no idea on things like .Net


Solution

  • I am assuming that you already have the schema for storing the users hash in some kind of user profile table?

    Let's say that this table is in the format as below:

    PersonID           int PrimaryKey
    PersonName         nvarchar(50)
    PersonPasswordHash varchar(128)
    PersonPasswordSalt nvarchar(10)
    

    then in your .net code (example in C#) you would go ahead and do the following when you are creating a new user

    string passwordPlain = txtPassword.Text; // This is the password entered by the user
    
    /* a work factor of 10 is default, but you can mention any thing from 4 to 31. 
       But keep in mind that for every increment in work factor the work increases 
       twice (its 2**log_rounds)
    */
    string passwordSalt = BCrypt.GenerateSalt(10);
    string passwordHash = BCrypt.HashPassword(passwordPlain, passwordSalt);
    
    // Now store the passwordHash and passwordSalt in the database for that user
    

    After you have the above values store the appropriate values in the database.

    When it is time to validate a login, retrieve the details about the passwordHash and passwordSalt from the database and you can verify as follows:

    string originalPasswordSalt; // retrieve its value from the DB
    string originalPasswordHash; // retrieve its value from the DB
    string givenPasswordPlain = txtPassword.Text; // given by the user during login
    string givenPasswordHash = BCrypt.HashPassword(givenPasswordPlain, originalPasswordSalt);
    
    if(givenPasswordHash.Equals(originalPasswordHash)) { // you have an valid user
    } else { // given login name or password is not valid
    }