Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypto/bcrypt: hashedPassword is not the hash of the given password

Tags:

bcrypt

hash

go

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
}
like image 406
Melih Mucuk Avatar asked Feb 22 '16 14:02

Melih Mucuk


3 Answers

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).

like image 96
Danilo Avatar answered Oct 24 '22 05:10

Danilo


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.

like image 34
Datsik Avatar answered Oct 24 '22 07:10

Datsik


My mistake was thinking that it compared two bcrypt hashedpasswords, rather than a hashedpassword and your unencrypted password converted to binary -- hope that helps someone out there!

like image 22
howard Avatar answered Oct 24 '22 07:10

howard