Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bcrypt hashedSecret too short to be a bcrypted password

Tags:

bcrypt

go

I want to create a user authentication system using Go and I am stuck with logging into an account. I use bcrypt to hash passwords than I save it to the database (MySQL). The problem shows when I want to compare it with an inserted password. I have this error: hashedSecret too short to be a bcrypted password. I don't know what I'm doing wrong. Here is my code:

models.go

type User struct {
    ID       string `json:"id"`
    Username string `json:"username"`
    Password string `json:"password"`
    IsAdmin  bool   `json:"is_admin"`
}

user-routes.go (login func)

err := db.QueryRow("SELECT Password FROM Users WHERE Username = ?", user.Username).Scan(&storedPass)
    if err != nil {
        log.Fatal(err)
    }
    // hashed password
    fmt.Println(storedPass, []byte(storedPass))
    err = bcrypt.CompareHashAndPassword([]byte(storedPass), []byte(user.Password))
    if err != nil {
        // Here is error
        fmt.Println(err.Error())
    }

user-routes.go (register func)

stmt, err := db.Prepare(`INSERT INTO Users(Username, Password, IsAdmin) VALUES (?, ?, 0)`)
    if err != nil {
        log.Fatal(err)
    }
hash, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 10)
res, err := stmt.Exec(user.Username, string(hash))

It looks like the error is when I compare hashed password with an inserted password. Also, I save a password to a database without any errors.

+----+----------+----------------------------------------------------+---------+
| ID | Username | Password                                           | IsAdmin |
+----+----------+----------------------------------------------------+---------+
| 38 | test2    | $2a$10$5WwRQahtjgmaeIKRGXGZNOLVAv5EXUidRwbnZeryq9e |       0 |
+----+----------+----------------------------------------------------+---------+
like image 931
xaos_xv Avatar asked Oct 19 '25 10:10

xaos_xv


1 Answers

bcrypt produces hashes of 59-60 bytes (see this answer for details). In order to store the hash as varchar, you need to ensure its size is sufficient. According to your comment, you use varchar(50), which is not enough, and that's the reason that changing its size fixed your problem.

like image 169
Yury Fedorov Avatar answered Oct 22 '25 04:10

Yury Fedorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!