Bcrypt generates different hashes for the same password

I am using Bcrypt under Go to Hash and compare the password given by the user. The thing is in the login, when I compare the password with CompareHashAndPassword it never matches, so it always says the password is wrong. It is assumed that based on the concept of a hash with the same input, we will have the same result and this is not my case.

** My code for hash (in registration) **

bs, err := bcrypt.GenerateFromPassword([]byte(Password), bcrypt.MinCost)

      

What I've done

  • Send as password: 12345
  • When I type bs I get:

    Attempt 1: [36 50 97 36 48 52 36 49 104 78 117 77 56 73 113 99 114 78 99 111 100 57 57 120 101 69 117 118 117 103 87 108 68 76 88 70 119 110 65 116 68 108 118 57 68 86 81 88 77 50 71 78 101 81 104 65 54 67 107 121]

    Attempt 2: [36 50 97 36 48 52 36 47 50 84 70 73 120 56 70 67 116 69 101 48 113 86 89 103 89 119 71 97 46 120 77 116 83 86 57 56 112 122 66 103 46 106 74 104 10 8 82 113 117 85 110 51 103 115 107 109 102 109 49 115 113]

    Attempt 3: [36 50 97 36 48 52 36 51 103 97 117 103 49 74 110 113 85 101 113 54 121 69 108 109 72 76 108 72 46 85 121 65 87 122 103 119 88 71 82 114 56 105 65 6 9 49 113 73 112 52 48 85 69 85 47 118 56 56 47 48 67]

Correct me if I am wrong, but in all attempts the result should not be the same?

Then I store these values ​​in the database and these are the values ​​for each try:

  • $ 2a $ 04 $ 1hNuM8IqcrNcod99xeEuvugWlDLXFwnAtDlv9DVQXM2GNeQhA6Cky
  • $ 2a $ 04 $ / 2TFIx8FCtEe0qVYgYwGa.xMtSV98pzBg.jJhlRquUn3gskmfm1sq
  • $ 2a $ 04 $ 3gaug1JnqUeq6yElmHLlH.UyAWzgwXGRr8iAE1qIp40UEU / V88 / 0C

Then, to compare the password, in the login:

err := bcrypt.CompareHashAndPassword(user.Password, []byte(p))

      

user.Password is [] byte, this value is called from the database

Thank. p is the user submitting the password to the form

+3


source to share


1 answer


Bcrypt generates a random salt (which is included in the resulting hash). Therefore, each time with a different purpose, it is different.

You need to use bcrypt.CompareHashAndPassword

to compare hashed password and plaintext password.



The first argument bcrypt.CompareHashAndPassword

is the hashed password, the second is the plaintext password. So you passed them in the wrong order.

WARNING : The cost you have chosen 4

is extremely low. Try to choose something like 10

or more.

+8


source







All Articles