使用 Go 根据 /etc/shadow 文件中的哈希密码验证密码
php小编子墨今天为大家介绍一种使用Go语言验证密码的方法,这个方法是基于读取/etc/shadow文件中的哈希密码进行验证的。在日常开发中,密码验证是一个非常重要的功能,而使用Go语言可以快速、高效地实现密码验证的功能。通过读取/etc/shadow文件中的哈希密码并进行比对,我们可以确保用户输入的密码与存储在系统中的密码一致。本文将详细介绍这个方法的实现过程,希望能对大家有所帮助。
问题内容
我目前在 /etc/shadow
文件中的密码格式类似于 $6$icnb6xpt8xjwc$ai9rq5hqpep.juts/tubhk/oi7so/s1aa.ihgbjhn12qmt5p44x5or86pso9/opbo4cmo0at4xumc0ycapo8 7/
(sha512
加密密码)。我需要做的是验证密码(用户提供的密码和当前的哈希密码)。我正在 go
上实现这个。
我试图实现这一目标的方法是,获取用户提供的密码,使用与 /etc/shadow
中相同的盐对其进行哈希处理,并检查它们是否相似或不同。如何生成相同的哈希值并验证密码?
下面是我正在做的粗略代码(根据 amadan 对编码的评论进行了更新)
// this is what is stored on /etc/shadow - a hashed string of "test" myPwd := "$6$IcnB6XpT8xjWC$AI9Rq5hqpEP.Juts/TUbHk/OI7sO/S1AA.ihgBjHN12QmT5p44X5or86PsO9/oPBO4cmo0At4XuMC0yCApo87/" // getting the salt salt := strings.Split(myPwd, "$")[2] encoding := base64.NewEncoding("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").WithPadding(base64.NoPadding) decodedSalt, err := encoding.DecodeString(salt) // user provided password myNewPwd := "test" newHashedPwd, err := hashPwd512(string(myNewPwd), string(decodedSalt)) // comparision if (newHashedPwd == myPwd) { // password is same, validate it } // What I'm expecting from this method is that for the same password stored in the /etc/shadow, // and the same salt, it should return (like the one in /etc/shadow file) // AI9Rq5hqpEP.Juts/TUbHk/OI7sO/S1AA.ihgBjHN12QmT5p44X5or86PsO9/oPBO4cmo0At4XuMC0yCApo87/ func hashPwd512(pwd string, salt string) (string, error) { hash := sha512.New() hash.Write([]byte(salt)) hash.Write([]byte(pwd)) encoding := base64.NewEncoding("./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz").WithPadding(base64.NoPadding) hashedPwd := encoding.EncodeToString(hash.Sum(nil)) return hashedPwd, nil }登录后复制