【问题标题】:How to verify the password如何验证密码
【发布时间】:2021-07-30 07:15:53
【问题描述】:

在这段代码中,第一个函数是Findaccount(),它将在数据库中查找电子邮件地址和作为哈希值出现的密码。所以CompareHashAndPassword()比较哈希和密码。

现在在handler.go 文件中,我有一个名为loginData() 的函数,它允许用户登录。我这里有个问题。我调用了database.Findaccount(email, password, hash) 函数,但它只是验证电子邮件地址而不验证 正确的密码,并给我false 消息。

但是,如果我像 database.Findaccount(email, "1234", hash) 这样调用函数,它会验证电子邮件和密码。

如何解决这个问题,因为我无法记住每个密码。

db.go

func Findaccount(myEmail, myPassword, hash string) bool {
    collection := Connect.Database("WebApp2").Collection("dataStored")
    if err := collection.FindOne(context.TODO(), bson.M{"email": myEmail}).Decode(&Account); err != nil {
        fmt.Println("Enter the correct email or password")
    }
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(myPassword))
    return err == nil
}

handler.go

func HashPassword(password string) (string, error) {
    bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
    return string(bytes), err
}

func loginData(w http.ResponseWriter, r *http.Request) {
    email := r.FormValue("email")
    password := r.FormValue("password")
    hash, _ := HashPassword(password)
    match := database.Findaccount(email, password, hash) // here is a problem
    if match == false {
        fmt.Println("false")
    } else {
        fmt.Println("true")
    }
}

【问题讨论】:

  • 您应该从Account 中获取hash
  • 这里是哈希$2a$04$28kZ/RY.BhGyWQvWPAngduAhoZPjrsyE6zEDCufu1gClsHpCyXJeW

标签: go passwords


【解决方案1】:

根据documentation,这是bycrypt.CompareHashAndPassword()的func模式:

func CompareHashAndPassword(hashedPassword, password []byte) error

要使用它,您需要将hashedPassword(存储在数据库中的哈希密码)作为第一个参数值。

然后将请求参数中的password 放到第二个参数中。

func loginData(w http.ResponseWriter, r *http.Request) {
    email := r.FormValue("email")
    password := r.FormValue("password")
    match := database.Findaccount(email, password)
    if match == false {
        fmt.Println("false")
    } else {
        fmt.Println("true")
    }
}

func Findaccount(myEmail, myPassword string) bool {
    collection := Connect.Database("WebApp2").Collection("dataStored")
    if err := collection.FindOne(context.TODO(), bson.M{"email": myEmail}).Decode(&Account); err != nil {
        fmt.Println("Enter the correct email or password")
    }
    err := bcrypt.CompareHashAndPassword([]byte(Account.Password), []byte(myPassword))
    return err == nil
}

参见Findaccount()bcrypt.CompareHashAndPassword() 语句的第一个参数由Account.Password 填充,这是存储在数据库中的哈希密码。

【讨论】:

  • 一点盐适合那个食谱,不是吗?
  • @mh-cbon 如果在注册过程中使用盐对密码进行哈希处理,那么在登录过程中应该包含相同的盐。从 OP 问题,我假设根本不使用盐。可能需要更多细节来确认。
  • 是的,我同意。我当然想打开 OP 的眼睛,看看接下来可以做什么。答案确实回答了 OP,因此,我加了它。
  • @mh-cbon bcrypt 自动包含盐
  • @zerkms 不知道它这样做了....stackoverflow.com/questions/6832445/… 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2012-09-18
  • 2018-09-17
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
相关资源
最近更新 更多