KNgu
KNgu

Reputation: 375

BCrypt comparing two hashes not equal

I have this code:

u := models.Users{}

u = u.FindByEmail(login.Email)

password := []byte(login.Password)

hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { panic(err) }

err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(u.Password)) fmt.Println(err)

I end up getting this error: crypto/bcrypt: hashedPassword is not the hash of the given password

However I previously saved my model to have the same hash as "admin", but when I run my application, it tells me it is not equal.

Upvotes: 3

Views: 6149

Answers (1)

David Budworth
David Budworth

Reputation: 11626

Re-read the docs carefully.

CompareHashAndPassword compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.

Basically, it is saying that you should compare the hash you have stored against the plain text password.

you probably want:

u := models.Users{}

u = u.FindByEmail(login.Email)

plainPassword := []byte(login.Password)
// Assumes that u.Password is the actual hash and that you didn't store plain text password.
err = bcrypt.CompareHashAndPassword([]byte(u.Password), plainPassword)

fmt.Println(err)

Upvotes: 5

Related Questions