[Ethereum] How to verify a signature with the web3 javascript API


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

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

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.

Related Topic