Go中与Scala SHA512哈希等效的方法是什么?

huangapple go评论87阅读模式
英文:

What is the Go equivalent of Scala SHA512 hash?

问题

Scala中,我们有一段代码,它使用SHA512哈希字符串,然后以十六进制格式填充字符串:

String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-512").digest("MyStringToBeHashed".getBytes("UTF-8"))))

我在Go中使用crypto包对字符串进行哈希:

package main

import (
    "crypto/sha512"
    "encoding/base64"
    "fmt"
)

func main() {
    hasher := sha512.New()
    hasher.Write([]byte("MyStringToBeHashed"))
    sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
    sha = fmt.Sprintf("%032x", sha)
    println(sha)
}

Scala中,我得到以下输出:

b0bcb1263862e574e5c9bcb88a3a14884625613410bac4f0be3e3b601a6dee78f5635d0f7b6eb19ba5a1d80142d9ff2678946331874c998226b16e7ff48e53e5

但在Go中:

734c79784a6a68693558546c79627934696a6f556945596c5954515175735477766a343759427074376e6a3159313050653236786d365768324146433266386d654a526a4d59644d6d59496d7357355f3949355435513d3d
英文:

In Scala we have a part of code that hash a string in SHA512 and then pad the string in Hexadecimal format:

String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-512").digest("MyStringToBeHashed".getBytes("UTF-8"))))

I hash string in Go using crypto package:

package main

import (
        "crypto/sha512"
        "encoding/base64"
)

func main() {
        hasher := sha512.New()
        hasher.Write([]byte("MyStringToBeHashed"))
        sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
        sha = fmt.Sprintf("%032x", sha)
        println(sha)
}

In Scala I get the below output:

b0bcb1263862e574e5c9bcb88a3a14884625613410bac4f0be3e3b601a6dee78f5635d0f7b6eb19ba5a1d80142d9ff2678946331874c998226b16e7ff48e53e5

But in Go:

734c79784a6a68693558546c79627934696a6f556945596c5954515175735477766a343759427074376e6a3159313050653236786d365768324146433266386d654a526a4d59644d6d59496d7357355f3949355435513d3d

答案1

得分: 5

附加的Base64编码是错误的。你要么想将哈希显示为Base64(即base64(hash)),要么想将哈希显示为十六进制字符串(即hex(hash)),但你实际上是将Base64编码的哈希显示为十六进制字符串(即hex(base64(hash)))。请改为以下方式:

sha := fmt.Sprintf("%032x", hasher.Sum(nil))
英文:

The additional base64 encoding is wrong. You either want to show the hash as base64 (i.e. base64(hash)) or you want to show the hash as hex string (i.e. hex(hash)) - but what you do instead is to show the base64 encoded hash as hex string (i.e. hex(base64(hash))). Simply do instead:

    sha := fmt.Sprintf("%032x", hasher.Sum(nil))

huangapple
  • 本文由 发表于 2022年8月3日 15:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/73217778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定