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 | +----+----------+----------------------------------------------------+---------+ 41 Answer
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.