bcrypt 生成不正确的哈希 - 我的用户输入处理是否正确?

bcrypt generates incorrect hashes - is my user-input processing correct?

我用 Go 编写了一个小程序,用于根据通过标准输入提供的密码生成 bcrypt 密码哈希。下面的最小示例:

package main

import (
    "bufio"
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func main() {

    fmt.Println("Enter password:")
    reader := bufio.NewReader(os.Stdin)
    inputPassword, _ := reader.ReadString('\n')

    inputPasswordBytes := []byte(inputPassword)
    hashBytes, _ := bcrypt.GenerateFromPassword(inputPasswordBytes, bcrypt.DefaultCost)

    hashStr := string(hashBytes)

    fmt.Println(hashStr)
}

在另一个程序(Go 网络服务器)中,我从 HTTP POST 请求中接受用户密码,并根据上面代码生成的哈希值对其进行测试,并保存到启动时加载的配置文件中,像这样:

func authenticateHashedPassword(inputPassword string) bool {

    configPasswordHashBytes := []byte(server.Config.Net.Auth.Password)
    inputPasswordBytes := []byte(inputPassword)
    err := bcrypt.CompareHashAndPassword(configPasswordHashBytes, inputPasswordBytes)
    if err != nil {
        return false
    }
    return true

}

然而,当我知道 inputPassword 是正确的时,这会报告失败。经过一番调查后,我发现当我使用该网站测试我的值时,我上面的初始 func main 生成了错误的输出:https://www.dailycred.com/article/bcrypt-calculator - 它说我生成的所有输出都与所需的密码不匹配.

我假设我这样做时字符编码或其他细节有问题 []byte(inputPassword) - 它可能包括尾随行尾吗?

不幸的是,我无法逐步调试我的程序,因为 Visual Studio Code 的 Go 语言工具和调试器不支持使用标准 IO:https://github.com/Microsoft/vscode-go/issues/219

bufio Reader.ReadString method returns the data up to and including the \n delimiter. The \n is included in the password. Use strings.TrimSpace 到 trim \n 以及用户可能输入的任何空格。

package main

import (
    "bufio"
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func main() {

    fmt.Println("Enter password:")
    reader := bufio.NewReader(os.Stdin)
    inputPassword, _ := strings.TrimSpace(reader.ReadString('\n'), "\n"))

    inputPasswordBytes := []byte(inputPassword)
    hashed, _ := bcrypt.GenerateFromPassword(inputPasswordBytes, bcrypt.DefaultCost)

    fmt.Printf("%s\n", hashed)
}