gotype-conversionbigintegersha-3

How to convert an sha3 hash to an big integer in golang


I generated a hash value using sha3 and I need to convert it to a big.Int value. Is it possible ? or is there a method to get the integervalue of the hash ?

the following code throws an error that cannot convert type hash.Hash to type int64 :

package main 

import (
"math/big"
"golang.org/x/crypto/sha3"
"fmt"

)
func main(){

  chall := "hello word"
  b := byte[](chall)
  h := sha3.New244()
  h.Write(chall)
  h.Write(b)
  d := make([]byte, 16)
  h.Sum(d)
  val := big.NewInt(int64(h))
  fmt.Println(val)

}



Solution

  • (See Peter's comment for the simpler version of this.)

    Interpreting a series of bytes as a big.Int is the same as interpreting a series of decimal digits as an arbitrarily large number. For example, to convert the digits 1234 into a "number", you'd do this:

    The same applies to bytes. The "digits" are just base-256 rather than base-10:

    val := big.NewInt(0)
    for i := 0; i < h.Size(); i++ {
        val.Lsh(val, 8)
        val.Add(val, big.NewInt(int64(d[i])))
    }
    

    (Lsh is a left-shift. Left shifting by 8 bits is the same as multiplying by 256.)

    Playground