node.jsbackendbcryptlogin-page

Can I use bcrypt to compare passwords which are already hashed?


I’m a newbie to nodejs and struggling with an issue regarding password hashing. I am recreating a website using ReactJS and using nodejs for the backend. There is a table in the database called userprofiles. It has email, hashed password, firstname, lastname etc. I am trying to create the login page as a start and I only need a login page not a register page, because I already have the user table from the previous database. I used bcrypt to compare the hashed password but those passwords not hashed by bcrypt because previous website was created using php since it used different method to hash the password. My question is can I use bcrypt.compare to compare my password when login?

Can I still use bcrypt? Please advise me on this matter, thanks.


Solution

  • If this is the bcrypt.compare() that you are using, then bcrypt.compare() does not compare two hashed passwords.

    It compares a plain text password to a hashed password. It uses the stored parameters (such as salt) that are in the hashed password in order to make a hash of the plain text password using the same salt so it can then compare the two hashes.

    Since hashed passwords would typically only be created on your server, one can usually adapt your code to accommodate this. The user doesn't know the salt used so they will submit a plain text password (usually protected in transport by https).

    One possibility if you can't avoid comparing two bcrypt hashed passwords is to just directly compare the two hashes using something like crypto.timingSafeEqual(). The bcrypt has consists of an algorithm identifier, an iteration level, a salt and the hash. Two identical original passwords should result in the same bcrypt hash value (same algorithm, same salt, same iteration level, same hash and thus same binary value). But, I haven't tried that myself.

    This is what a bcrypt hash value looks like:

    Resultant hashes will be 60 characters long and they will include
    the salt among other parameters, as follows:
    
    $[algorithm]$[cost]$[salt][hash]
    
    2 chars hash algorithm identifier prefix. "$2a$" or "$2b$" indicates BCrypt
    Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
    16-byte (128-bit) salt, base64 encoded to 22 characters
    24-byte (192-bit) hash, base64 encoded to 31 characters
    
    $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
     |  |  |                     |
     |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
     |  |  |
     |  |  salt = nOUIs5kJ7naTuTFkBy1veu
     |  |
     |  cost-factor => 10 = 2^10 rounds
     |
     hash-algorithm identifier => 2b = BCrypt