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

Go bcrypt生成不正确的哈希-我的用户输入处理是否正确?,go,stdin,bcrypt,Go,Stdin,Bcrypt,我在Go中编写了一个简短的程序,从stdin提供的密码生成bcrypt密码散列。下面是一个简单的例子: package main import ( "bufio" "fmt" "golang.org/x/crypto/bcrypt" ) func main() { fmt.Println("Enter password:") reader := bufio.NewReader(os.Stdin) inputPassword, _ := rea

我在Go中编写了一个简短的程序,从stdin提供的密码生成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 web服务器)中,我从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
生成了错误的输出:-它说我生成的所有输出都与所需的密码不匹配

我假设当我执行
[]字节(inputPassword)
时,字符编码或其他细节出现了问题-可能包括尾随行结尾吗

不幸的是,我无法单步调试我的程序,因为Visual Studio代码的Go语言工具和调试器不支持使用标准IO:

该方法返回的数据最多包含\n分隔符。密码中包含
\n
。用于修剪用户输入的
\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)
}
该方法返回小于或等于
\n
分隔符的数据。密码中包含
\n
。用于修剪用户输入的
\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)
}

我的程序省略了一行,在那里我做了
hashStr=string(hashBytes)
。在这两种情况下,输出外观(bcrypt值的字符范围和文本长度)是相同的。当我在Windows上运行时,
inputPassword
值包含一个尾随的
\r
-因此我使用
strings.TrimSpace()
而不是
TrimSuffix
。事实证明,我的真实代码中还有第二个问题(在我发布的示例中不可见)我错误地隐藏了
inputPassword
值。考虑到编译器对其他一切(例如未使用的变量)的要求有多严格,我很惊讶Go没有警告我。我的程序省略了一行,我在那里做了
hashStr=string(hashBytes)
。输出外观(bcrypt值的字符范围和文本长度)在这两种情况下都是相同的。当我在Windows上运行时,
inputPassword
值包含一个尾随的
\r
-所以我使用
strings.TrimSpace()
而不是
TrimSuffix
。事实证明我的真实代码中还有一个次要问题(在我发布的示例中不可见)我错误地隐藏了
inputPassword
值。考虑到编译器对其他所有内容(例如未使用的变量)的严格程度,我很惊讶Go没有警告我这一点。