Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bcrypt generating different hash for the same password

Tags:

bcrypt

hash

go

I am using Bcrypt in Go to hash and compare the password given by the user. The thing is in the login, when I compare the password using CompareHashAndPassword it never matches so always says that the password is incorrect. Based on the concept of hash is supposed that with the same input we will have anytime the same output, and this is not my case.

**My code to hash (in the sign up) **

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

What I did

  • Send as password: 12345
  • When I print 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 that attempts the result should not be the same?

Then, I save that values in the database and these are the values for each attempt:

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

Then, to compare the password, in the login:

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

user.Password is a []byte this value is conusulted from the database

Thank you p is the password send in the form by the user

like image 483
Sredny M Casanova Avatar asked Sep 25 '26 01:09

Sredny M Casanova


1 Answers

Bcrypt generates a random salt (that is included as a part of the resulting hash). So it is different every time with purpose.

You need to use bcrypt.CompareHashAndPassword to compare the hashed password and the plaintext password.

The first argument of bcrypt.CompareHashAndPassword is the hashed password, the second is the plaintext password. So you passed them in the wrong order.

WARNING: the cost you've chosen 4 is extremely low. Consider choosing something like 10 or over.

like image 91
zerkms Avatar answered Sep 27 '26 23:09

zerkms