Web3 JavaScript API – How to Verify a Signature

cryptographysignatureweb3js

Using the javascript web3 API I can create a signature like this:

> web3.eth.sign(eth.coinbase, "0xdeadbeef")
"0xd3fe64b6f0920593cc4afb1321d592ae91e25fe1a0216e9002a4a6580fb2698c5ec62491c62557b8cc8f64533a5097b3ffb68208952b30cb27ed0a56ae21682201"

Now I'd like to verify that the signature is correct; doing so in a contract is already documented elsewhere, but I am looking for a way to do this using web3. (How) can this be done?

Best Answer

web3 does not support this feature yet, but it might be coming with web3 1.0.

In the meantime you can use ethereumjs-utils ecrecover feature. Note that this function expects v to be in {27, 28}, and since your signature comes from geth, (since it doesn't return signatures in the canonical format yet) you will have to add 27 to your v.

Given a signature sgn of a the hashed message msg, you can use the ethereumjs-util library like this:

r = utils.toBuffer(sgn.slice(0,66))
s = utils.toBuffer('0x' + sgn.slice(66,130))
v = utils.toBuffer('0x' + sgn.slice(130,132))
m = utils.toBuffer(msg)
pub = utils.ecrecover(m, v, r, s)
adr = '0x' + utils.pubToAddress(pub).toString('hex')

To do the verification in a solidity contract, check out this answer.