douzhai7873 2014-10-05 06:08
浏览 270
已采纳

在Go中生成crypt()sha512哈希

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
", 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条回答 默认 最新

  • douyou8266 2014-10-05 13:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效