Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SHA1 Hex to Base 16 Integer

Tags:

hex

go

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?

like image 554
Zohar Arad Avatar asked Sep 13 '15 03:09

Zohar Arad


Video Answer


2 Answers

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)
}
like image 118
HectorJ Avatar answered Nov 15 '22 11:11

HectorJ


try this 🙂

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)

Example Output...

fcbc340d999e751840e17f862cc9eaf826cc6079
fcbc340d999e751840e17f862cc9eaf826cc6079
like image 21
Ritwik Avatar answered Nov 15 '22 10:11

Ritwik