Last active
July 24, 2024 22:40
-
-
Save alexanderattar/29bef134239d5760b8d1fcc310b632be to your computer and use it in GitHub Desktop.
Example of how to sign a message with web3 and recover the address that signed it
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
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 | |
ethUtil.bufferToHex(msgHash) | |
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
2023 examples in both golang and js: https://www.ethsigpublicaddress.com/