douchuifk90315 2015-09-13 03:13
浏览 665
已采纳

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

I need some help porting an algorithm from Ruby to Go.

In Ruby I have:

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

Which creates a SHA1 hex string, converts it to an integer in base 16 and then back to a string in base 32.

How do I achieve the same in Go?

  • 写回答

2条回答 默认 最新

  • doulou1970 2015-09-13 07:50
    关注

    Here is an example code (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)
    }
    

    I tested it agaisnt this Ruby script and the ouput matches :

    require 'digest'
    
    str = "example"
    hex = Digest::SHA1.hexdigest(str).to_i(16)
    
    puts hex.to_s(32)
    

    Edit : here is my original answer, which reproduces every step from the ruby script, but two of them are unnecessary (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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题