Search code examples
javascripthashethereumweb3js

What hash encryption algorithm does web3 use? ethereumjs-util Sha3 returns different result


I'm trying to properly sign an authentication method through web3's signPersonalMessage function. However, eth-sig-util's package which correctly authenticates does not produce the same hash with the same data as both SHA3-256 and Keccak-256.

For example, if i try to hash: 0x664f5f32784d335a69596e4f416c636373496859377054744f704c6e54666a314c70314a4f364d565f4638

My result with Keccak256: 5dc2751b78fdb82a0986ad2a8e6cc774458d7a096e8eafd3ab6937146b7d2eec

My result with SHA3-256: 6fa399a29899ebab112d562526b9b735f0cf7ce4bdc5a96edfcc48572b8d3e7b

My result with the library's Sha3 function: 40de9eb1ead6a6299af30cdf51eca39d44be214ce7431c93ff546cf5fb1ef0fb

This is the only issue I can think of, I also often encountered an 'Incorrect v length' or 'invalid signature length' error before when I tried to sign and authenticate with Keccak.


Solution

  • My guess is that you're using web3.js 0.20.x and failing to pass the encoding parameter. That will treat the input as a string, which probably isn't what you want:

    web3.sha3('0x664f5f32784d335a69596e4f416c636373496859377054744f704c6e54666a314c70314a4f364d565f4638', { encoding: 'hex' })
    "0x40de9eb1ead6a6299af30cdf51eca39d44be214ce7431c93ff546cf5fb1ef0fb"