How to use the verify function correctly in Bcrypt

1.6k Views Asked by At

Good time I use bcrypt to encrypt passwords in .net mvc(c#) In sign-up, I use the following code:

string salt = BCrypt.Net.BCrypt.GenerateSalt(12);
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(enteredPassword, salt);

and At this point, the hashedPassword is stored in the database

The question I have at this stage is whether salt needs to be stored in the database?

I also use the following code in the login:

--hashedPassword is read from the database
 bool verify = BCrypt.Net.BCrypt.Verify(password, hashedPassword,false, hashType : HashType.SHA512);
        
        
     if (verify)
     {
     }
     else
     {
     }

The next question is whether the verification was done correctly? Should I not use salt at this stage? I did not use salt in the login

And the last question is whether it is correct to use hashType: HashType.SHA512 and enhancedEntropy: false in the verify function? Are these settings the best settings?

2

There are 2 best solutions below

0
martinstoeckli On

Not absolutely sure if you refer to this bcrypt.net library, but it is most likely not necessary to generate the salt on your own, and the salt is surely included in the resulting hash-value. So you can just write:

string passwordHash =  BCrypt.HashPassword("my password");
bool isPasswordCorrect = BCrypt.Verify("my password", passwordHash);
0
Chris McKee On

If you're using something like .net 5 you may find its simpler to import the static in the class and call the hash/verify using that

e.g.

using System;
using static BCrypt.Net.BCrypt;

namespace BcryptNet5
{
    class Program
    {
        static void Main(string[] args)
        {
            var hash = HashPassword("Test");
        }
    }
}

As the previous answer stated; don't generate you're own salt. Salts are stored alongside the hash as part of the bcrypt standard and the library takes care of generating the salts for you. The only reason that method exists is for advanced testing.


Maintainer BCrypt.Net