I encrypt user's password and save to db. Then to user login, compare hashed password and plain password, I'm getting crypto/bcrypt: hashedPassword is not the hash of the given password
error. Whats 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
}
I cannot tell which is which, but in your compare function, ensure that 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 ensure you're actually getting something to hash, you could be getting a blank password but not realizing it because the hash will still look full.
My bet is that user.Password
is empty in your Register
function before you pass it to encryptPassword
thus leading to hashes on empty passwords like the one you provided ($2a$10$rqHJJTHsxMbtX/5ZjG1mFuWyYbUDW1PLbfwQRN0uChwes38c/0m3e
).