密码哈希与哈希尝试不匹配
时间:2024-03-27
浏览:153
作者:佚名
在 Go 服务器上存在密码哈希不匹配的问题,在创建用户时对密码哈希后存储,但在登录时哈希后的密码却不同。开发人员推测这是指针使用不当导致的,但进一步的调试表明可能与将字符串切片转换为字节切片的方式有关。在这种情况下,建议使用 http.Request.Form.Get("key") 获取字符串形式的数据,然后使用 []byte() 转换为字节切片。
我在 go 服务器上有一个“createuser”函数,我在其中散列新用户的密码并存储通过 post 发送的表单中的数据。
用户及其统计数据的数据库被提取并转换为包含结构及其信息的字符串映射。它看起来像这样:
var userstruct struct {
users map[string]struct {
admin, moderator, root bool
pass *string
}
}
它是指针的原因是因为稍后我可能想更改密码。
因此,当我创建新用户时,我将 post 请求中的 json 解组到如下结构中:
var newuser struct{
username, password string
isadmin, ismoderator bool
}
我使用 json.newdecoder 将其解码为结构,如下所示:
err := json.newdecoder(r.body).decode(&newuser)
然后,我对其进行哈希处理并使用 sha、json.marshalindent 和 ioutil.writefile 存储结果:
sha := sha1.new()
sha.write([]byte(newuser.password))
var hashedpass string;
hashedpass = hex.encodetostring(sha.sum(nil))
fmt.println(hashedpass)
userstruct.users[newuser.username] = struct {
admin, moderator, root bool
pass *string
}{
admin: newuser.isadmin,
moderator: newuser.ismoderator,
root: false,
pass: &hashedpass,
}
fmt.println(*userstruct.users[newuser.username].pass)
file, _ := json.marshalindent(userstruct, "", " ")
_ = ioutil.writefile("userinfo.json", file, 0644)
然后,在登录端,我将解析后的凭据形式的字符串切片转换为字节切片,并将用户名/密码与数据库中存储的用户名/密码进行比较。
这里,这表明我可以使用 gob 编码器:
r.parseform()
sha := sha1.new()
buf := &bytes.buffer{}
gob.newencoder(buf).encode(r.form["password"])
bufbytes := buf.bytes()
sha.write(bufbytes)
bs := sha.sum(nil)
fmt.println(hex.encodetostring(bs))
usrjson, _ := ioutil.readfile("userinfo.json")
var userstruct struct {
users map[string]struct {
root, admin, moderator bool
pass *string
}
}
json.unmarshal(usrjson, &userstruct)
username := strings.tolower(strings.join(r.form["username"], "")
然后我比较用户名和密码。不过,密码比较是我们需要关注的唯一问题:
if *userStruct.Users[username].Pass == hex.EncodeToString(bs) {
}
尝试调试时,我在用户创建函数、和用户登录函数中输出了哈希结果。
我用于示例的密码是 myverysecretpassword。
存储的哈希如下所示:
7816b9b6485dd785aab9f91a31a0b80997ed44b9
密码尝试如下所示:
08618c3225370a2205d698d06df48ba4b820c1d4
当我越来越深入地研究这一点时,我意识到这可能是我对指针/地址的使用,但无论如何我仍然感到困惑。
这是怎么回事?
解决方案
看起来我不太明白关于将字符串切片转换为字节切片的帖子答案底部的这一点:
Gob 简单明了。但是,该格式只能用其他 Go 代码读取。
多读几遍就明白了,Go 编码并不意味着将字符串切片直接转换为字节切片。
根据评论,Gob是一个编码器,而不是字符串切片到字节切片转换器。
我可以使用 http.Request.Form.Get("key") 来代替,以字符串形式获取数据,并使用 []byte() 将其转换为字节。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
