Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of how to sign a message with web3 and recover the address that signed it
var ethUtil = require('ethereumjs-util');
var data = 'Login';
var message = ethUtil.toBuffer(data);
var msgHash = ethUtil.hashPersonalMessage(message);
var privateKey = new Buffer('62debf78d596673bce224a85a90da5aecf6e781d9aadcaedd4f65586cfe670d2', "hex")
var sig = ethUtil.ecsign(msgHash, privateKey);
var signature = ethUtil.toBuffer(sig)
var sigParams = ethUtil.fromRpcSig(signature)
var publicKey = ethUtil.ecrecover(msgHash, sigParams.v, sigParams.r, sigParams.s)
var sender = ethUtil.publicToAddress(publicKey)
var addr = ethUtil.bufferToHex(sender)
// Get hashed message in string form
var Web3 = require('web3');
var web3 = new Web3();
var ethUtil = require('ethereumjs-util');
// Private Key
var pKey = "62debf78d596673bce224a85a90da5aecf6e781d9aadcaedd4f65586cfe670d2"
var pKeyx = new Buffer(pKey, "hex")
// Shared Message
var message = 'Login'
var messageHash = web3.sha3(message)
var messageHashx = new Buffer(messageHash.replace("0x", ""), "hex")
// Signed Hash
var signedMessage = ethUtil.ecsign(messageHashx, pKeyx)
var signedHash = ethUtil.toRpcSig(signedMessage.v, signedMessage.r, signedMessage.s).toString("hex")
// Recover Address
var sigDecoded = ethUtil.fromRpcSig(signedHash)
var recoveredPub = ethUtil.ecrecover(messageHashx, sigDecoded.v, sigDecoded.r, sigDecoded.s)
var recoveredAddress = ethUtil.pubToAddress(recoveredPub).toString("hex")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.