Crypto / bcrypt: hashedPassword is not a hash of this password

I encrypt the user password and save the db. Then, to log in, compare the hashed password and a simple password, I get a crypto/bcrypt: hashedPassword is not the hash of the given password error crypto/bcrypt: hashedPassword is not the hash of the given password . What's wrong?

 func encryptPassword(password string) (string, error) { bytePass := []byte(password) hashedPassword, err := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost) if err != nil { log.Printf("ERROR:EncryptPassword: %s", err.Error()) } return string(hashedPassword), err } func (i *Impl) Register(user User) bool { hashedPass, err := encryptPassword(user.Password) if err != nil { return false } user.Password = hashedPass if err := i.DB.Create(&user).Error; err != nil { log.Printf("ERROR:Register: %s", err.Error()) return false } return true } func (i *Impl) Login(email string, password string) (User, error) { var user User i.DB.Where("email = ?", email).First(&user) err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) if err != nil { log.Printf("ERROR:Login: %s", err.Error()) return User{}, err } return user, err } 
+6
source share
2 answers

My bet is that user.Password empty in your Register function before passing it to encryptPassword , which will result in hashes for empty passwords like the one you provided ( $2a$10$rqHJJTHsxMbtX/5ZjG1mFuWyYbUDW1PLbfwQRN0uChwes38c/0m3e ).

+3
source

I can’t say what it is, but in your comparison function, make sure you have the variables in the right place.

 bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) Must be the already hashed PW ^ ^ Plain Text Password to compare 

Also make sure that you really get something hash, you can get an empty password, but don't understand it, because the hash will still look full.

0
source

All Articles