Created
September 20, 2021 22:17
-
-
Save JayWelsh/cb865ae5ab47e85a2a23164f1b3f9aa4 to your computer and use it in GitHub Desktop.
An example of how to verify a signed message on Ethereum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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