英文:
Generating crypt() sha512 hashes in Go
问题
我正在使用GoLang开发我的授权模块。之前我们使用的是带有crypt函数的PHP5。哈希值是使用SHA-512生成的:
$6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
并且以这种方式存储在数据库中。但现在我需要在GoLang中实现相同的功能。我在Google上搜索并尝试了不同的方法,例如:
t512 := sha512_crypt.Crypt("rasmuslerdorf", "$6$usesomesillystringforsalt")
fmt.Printf("hash: %v\n", t512)
但是它们生成的结果都不同。谁能帮助我们进一步解决问题?
我们希望能够验证和创建与PHP版本相同的哈希值。
提前感谢。
英文:
I am working on my authorization module in GoLang. Before we used PHP5 with the crypt function. The hash was generated like SHA-512:
$6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
And stored like that in the database. But now I need make it work also in GoLang. I have searched on Google and tried different things, such as:
t512 := sha512_crypt.Crypt("rasmuslerdorf", "$6$usesomesillystringforsalt$")
fmt.Printf("hash: %v\n", t512)
But all generate different things. Who can help us further?
We want validate and create hashes like the php version.
Thanks in advance.
答案1
得分: 9
osutil
库(https://github.com/kless/osutil)支持所有crypt()
哈希类型。
你可以使用以下PHP代码生成密码哈希:
echo crypt('rasmuslerdorf', '$6$usesomesillystringforsalt');
这段代码生成以下哈希值:
$6$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
在Go语言中,可以这样实现:
package main
import (
"fmt"
"github.com/kless/osutil/user/crypt/sha512_crypt"
)
func main() {
c := sha512_crypt.New()
hash, err := c.Generate([]byte("rasmuslerdorf"), []byte("$6$usesomesillystringforsalt"))
if err != nil {
panic(err)
}
fmt.Println(hash)
}
运行时,它也会生成正确的哈希值:
$6$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
希望这回答了你的问题。
在实现时,请注意只使用了盐值的前16个字符,因此对于盐值usesomesillystri
,会返回相同的哈希值。请确保在生产代码中选择随机的盐值。
英文:
The osutil
library at https://github.com/kless/osutil has support for all crypt()
hash types.
Your password hash can be produced with the following php code:
echo crypt('rasmuslerdorf', '$6$usesomesillystringforsalt');
This code produces the following hash:
$6$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
This can be reproduced in Go like this:
package main
import (
"fmt"
"github.com/kless/osutil/user/crypt/sha512_crypt"
)
func main() {
c := sha512_crypt.New()
hash, err := c.Generate([]byte("rasmuslerdorf"), []byte("$6$usesomesillystringforsalt"))
if err != nil {
panic(err)
}
fmt.Println(hash)
}
When run, it also produces the correct hash:
$6$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
I hope this answers your question.
While implementing this please note that only 16 characters are used from the salt, so the same hash is returned for the salt usesomesillystri
. Make sure that you choose random salts in the production code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论