将SHA1十六进制转换为16进制整数

5

我希望你能够将一个算法从Ruby翻译成Go。

在Ruby中,我有以下代码:

hex = Digest::SHA1.hexdigest(str).to_i(16)
hex.to_s(32)

这段代码生成一个SHA1十六进制字符串,将其转换为十六进制整数,然后再转换为32进制字符串。

在Go语言中如何实现同样的功能?


2
我们是在讨论结果的32进制表示还是Base32编码?如果您能提供一些示例输入和输出就更好了。 - icza
为了快速测试,运行Ruby代码并将str =“example”作为输入,输出结果为“od4po9p9ec57v03uve37da9dpdnokfsf”。 - HectorJ
使用步骤:str = "example" 生成的十六进制摘要为 => "c3499c2729730a7f807efb8676a92dcb6f8a3f8f",to_i => 1114894757552854782121625437503858766054806929295,to_s => "od4po9p9ec57v03uve37da9dpdnokfsf"。 - HectorJ
2个回答

9

这里是一个示例代码(playground:https://play.golang.org/p/izBIq97-0S):

package main

import (
    "crypto/sha1"
    "encoding/base32"
    "fmt"
    "strings"
)

func main() {
    // Input
    exampleString := "example"

    // SHA1 hash
    hash := sha1.New()
    hash.Write([]byte(exampleString))
    hashBytes := hash.Sum(nil)

    // Conversion to base32
    base32str := strings.ToLower(base32.HexEncoding.EncodeToString(hashBytes))

    fmt.Println(base32str)
}

我对这个Ruby脚本进行了测试,输出结果相匹配:

require 'digest'

str = "example"
hex = Digest::SHA1.hexdigest(str).to_i(16)

puts hex.to_s(32)

编辑:这是我的原始答案,重现了从ruby脚本的每一步,但其中两个步骤是不必要的(playground:https://play.golang.org/p/tyQt3ftb1j):

package main

import (
    "crypto/sha1"
    "encoding/base32"
    "encoding/hex"
    "fmt"
    "math/big"
    "strings"
)

func main() {
    // Input
    exampleString := "example"

    // SHA1 hash
    hash := sha1.New()
    hash.Write([]byte(exampleString))
    hashBytes := hash.Sum(nil)

    // Hexadecimal conversion
    hexSha1 := hex.EncodeToString(hashBytes)

    // Integer base16 conversion
    intBase16, success := new(big.Int).SetString(hexSha1, 16)
    if !success {
        panic("Failed parsing big Int from hex")
    }

    // Conversion to base32
    base32str := strings.ToLower(base32.HexEncoding.EncodeToString(intBase16.Bytes()))

    fmt.Println(base32str)
}

谢谢!正是我想要的。 - Zohar Arad
@ZoharArad:我刚刚用更简短的代码进行了编辑:十六进制(字符串和大整数)步骤完全是不必要的。 - HectorJ

3

试试这个

h := sha1.New()
h.Write(content)
sha := h.Sum(nil)  // "sha" is uint8 type, encoded in base16

shaStr := hex.EncodeToString(sha)  // String representation

fmt.Printf("%x\n", sha)
fmt.Println(shaStr)

示例输出...

fcbc340d999e751840e17f862cc9eaf826cc6079
fcbc340d999e751840e17f862cc9eaf826cc6079

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接