dongyou2714 2018-05-10 03:06 采纳率: 0%
浏览 113
已采纳

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

I've written a short program in Go to generate a bcrypt password hash from a password provided via stdin. Minimal example below:

package main

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

func main() {

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

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

    hashStr := string(hashBytes)

    fmt.Println(hashStr)
}

In another program (a Go web-server) I accept the user's password from a HTTP POST request and test it against a hash generated with the code above and saved to a configuration file that's loaded at startup, like so:

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

}

However this reports failure when I know inputPassword is correct. After some investigation I saw that my initial func main above was generating the wrong output when I used this website to test my values: https://www.dailycred.com/article/bcrypt-calculator - it says all of the output I generate doesn't match the desired passwords.

I'm assuming there's something wrong going on with the character encoding or other details when I do []byte(inputPassword) - is it perhaps including the trailing line-ending?

Unfortunately I cannot step-through debug my program because Visual Studio Code's Go language tools and debugger does not support using standard-IO: https://github.com/Microsoft/vscode-go/issues/219

  • 写回答

1条回答 默认 最新

  • dongzichan2886 2018-05-10 03:40
    关注

    The bufio Reader.ReadString method returns the data up to and including the delimiter. The is included in the password. Use strings.TrimSpace to trim the and any whitespace that may have been entered by the user.

    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('
    '), "
    "))
    
        inputPasswordBytes := []byte(inputPassword)
        hashed, _ := bcrypt.GenerateFromPassword(inputPasswordBytes, bcrypt.DefaultCost)
    
        fmt.Printf("%s
    ", hashed)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)