Skip to content

Instantly share code, notes, and snippets.

@JayWelsh
Created September 20, 2021 22:17
Show Gist options
  • Save JayWelsh/cb865ae5ab47e85a2a23164f1b3f9aa4 to your computer and use it in GitHub Desktop.
Save JayWelsh/cb865ae5ab47e85a2a23164f1b3f9aa4 to your computer and use it in GitHub Desktop.
An example of how to verify a signed message on Ethereum
const util = require('ethereumjs-util');
const Web3 = require('web3');
// msg is the plaintext message (preimage)
// sig is the signed message
// walletAddress is the address that you want to verify the message comes from
const verifySignature = async (msg, sig, walletAddress) => {
const web3 = new Web3(null);
const res = util.fromRpcSig(sig);
const prefix = Buffer.from("\x19Ethereum Signed Message:\n");
const prefixedMsg = web3.utils.sha3(Buffer.concat([prefix, Buffer.from(String(msg.length)), Buffer.from(msg)]));
const pubKey = util.ecrecover(util.toBuffer(prefixedMsg), res.v, res.r, res.s);
const addrBuf = util.pubToAddress(pubKey);
const calcAddr = await util.bufferToHex(addrBuf);
return (walletAddress.toLowerCase() === calcAddr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment