Last active
March 5, 2024 21:33
-
-
Save belukov/3bf74d8e99fb5b8ad697e881fca31929 to your computer and use it in GitHub Desktop.
eth offline sign and verify message (without web3)
This file contains hidden or 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 ethUtils = require('ethereumjs-util'); | |
| const privateKey = '0x3c9229289a6125f7fdf1885a77bb12c37a8d3b4962d936f7e3084dece32a3ca1' | |
| const message = 'hello world'; | |
| function sign(message, pkey) { | |
| let mHash = ethUtils.sha3(message); | |
| let keyBuf = new Buffer(pkey.slice(2), 'hex'); | |
| let vrs = ethUtils.ecsign(mHash, keyBuf); | |
| let sigBuf = Buffer.concat([ vrs.r, vrs.s, ethUtils.toBuffer(vrs.v) ]); | |
| let signature = ethUtils.bufferToHex(sigBuf); | |
| return signature; | |
| } | |
| function getAddr(message, signature) { | |
| let mHash = ethUtils.sha3(message); | |
| let vrs = { | |
| r: new Buffer(signature.slice(2, 66), 'hex'), | |
| s: new Buffer(signature.slice(66, 130), 'hex'), | |
| v: Number( '0x' + signature.slice(130, 132) ) | |
| }; | |
| let pubkey = ethUtils.ecrecover(mHash, vrs.v, vrs.r, vrs.s); | |
| var addr = '0x' + ethUtils.publicToAddress(pubkey).toString('hex'); | |
| return addr; | |
| } | |
| let signature = sign(message, privateKey); | |
| console.log('signature', signature); | |
| let genesisAddr = '0x' + ethUtils.privateToAddress(new Buffer(privateKey.slice(2), 'hex')).toString('hex'); | |
| console.log('genesisAddr', genesisAddr); | |
| let signerAddr = getAddr(message, signature); | |
| console.log('signerAddr', signerAddr); | |
| console.log("Match: ", (signerAddr == genesisAddr ? 'yes' : 'no')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment