0

I'm trying to generate a sha3-512 hash in JS and check it in a golang server. However, cryptoJS is producing different hashes than golang.

CryptoJS:

CryptoJS.algo.SHA3.create().update("foo").finalize().toString(CryptoJS.enc.Hex)

Output:

1597842aac52bc9d13fe249d808afbf44da13524759477404c3592ee331173e89fe1cbf21a7e4360990d565fad4643cdb209d80fa41a91dea97e665022c92135


Golang:

hex.EncodeToString(crypto.SHA3_512.New().Sum([]byte("foo")))

Output:

666f6fa69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26

I expect these hashes to be equal, but they aren't

Edgar P-Yan
  • 78
  • 1
  • 8
user1044459
  • 57
  • 1
  • 5
  • Funny enough, i get a third value with Python‘s `hashlib.sha3_512(b“foo“).hexdigest()`... – Markus W Mahlberg Oct 06 '19 at 20:47
  • 2
    Assuming your Go package implements [hash.Hash](https://golang.org/pkg/hash/#Hash) you have to call Write before Sum (passing the hash input to Sum is nonsensical). – Peter Oct 06 '19 at 23:00
  • FWIW attempting to do `h.Sum(data)` is a *very* common mistake. I have fixed the same bug in 3 different code bases in 2 companies. – Joel Cornett Oct 27 '21 at 06:05

2 Answers2

5

I don't know whose sha3 package you're using. Here's what I get with this code:

package main

import (
    "fmt"
    "golang.org/x/crypto/sha3"
)

func main() {
    h := sha3.New512()
    h.Write([]byte("foo"))
    sum := h.Sum(nil)
    fmt.Printf("hash = %x\n", sum)
}

hash = 4bca2b137edc580fe50a88983ef860ebaca36c857b1f492839d6d7392452a63c82cbebc68e3b70a2a1480b4bb5d437a7cba6ecf9d89f9ff3ccd14cd6146ea7e7

Compare with Python3:

>>> import hashlib
>>> print(hashlib.sha3_512(b"foo").hexdigest())

which prints:

4bca2b137edc580fe50a88983ef860ebaca36c857b1f492839d6d7392452a63c82cbebc68e3b70a2a1480b4bb5d437a7cba6ecf9d89f9ff3ccd14cd6146ea7e7

torek
  • 448,244
  • 59
  • 642
  • 775
2

Obviously, your output is 134-width which should be 128-width.

Let us decode your output:

bytes, _ := hex.DecodeString("666f6fa69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
fmt.Printf("%s\n", bytes)

We found the output is foo��s̢:��ȵg�Zun�ɂO�XY����G\���:���L��@,:�X������u��(�&.

That means what you did actually is to output:

"foo" + sha3("")

where sha3_512("") is "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26" from Examples of SHA-3 variants.

p1gd0g
  • 631
  • 5
  • 16