我正在尝试使用web3.eth.sign()对字符串进行签名,然后从签名中获取我用它签名的公钥。为了做到这一点,我使用了中的ecrecover(),它返回一个缓冲区。当我在缓冲区上使用bufferToHex()时,它会给出一个长得不能成为地址的十六进制字符串-130个字符,包括'0x‘
web3.personal.unlockAccount(myAccount,pass)
msg = web3.sha3(aString)
sig = web3.eth.sign(myAccount,msg)
r = sig.slice(0, 66)
s = '0x' + sig.slice(66, 130)
v = '0x' + sig.slice(130, 132)
v = web3.toDecimal(v)
msg = ethJsUtil.toBuffer(msg)
addr = ethJsUtil.ecrecover(msg,v,r,s)
addr = ethJsUtil.bufferToHex(addr)我从使用私钥签名字符串,然后使用公钥进行签名验证的工作流。的答案中提取了大部分代码,但必须将'msg‘转换为缓冲区,否则ecrecover抛出一个类型错误。
我需要做什么才能将缓冲区从ecrecover转换为一个地址?
发布于 2017-02-28 15:38:57
ecrecover返回公钥,您需要使用pubToAddress将其转换为地址。
pub = ethJsUtil.ecrecover(msg, v, r, s);
addrBuf = ethJsUtil.pubToAddress(pub);
addr = ethJsUtil.bufferToHex(addrBuf);此外,您还可以使用fromRpcSig获取v, r, s
sig = web3.eth.sign(myAccount,msg)
res = ethJsUtil.fromRpcSig(sig)
pub = ethJsUtil.ecrecover(msg, res.v, res.r, res.s);请注意,web3.eth.sign在消息签名前添加了前缀(参见JSON-RPC规范)。
下面是如何手动添加它:
const util = require('ethereumjs-util')
const msg = new Buffer('hello');
const sig = web3.eth.sign(web3.eth.accounts[0], '0x' + msg.toString('hex'));
const res = util.fromRpcSig(sig);
const prefix = new Buffer("\x19Ethereum Signed Message:\n");
const prefixedMsg = util.sha3(
Buffer.concat([prefix, new Buffer(String(msg.length)), msg])
);
const pubKey = util.ecrecover(prefixedMsg, res.v, res.r, res.s);
const addrBuf = util.pubToAddress(pubKey);
const addr = util.bufferToHex(addrBuf);
console.log(web3.eth.accounts[0], addr);另一方面,testrpc (至少3.0.5版本)没有添加这样的前缀。
示例node.js + testrpc会话:
const util = require('ethereumjs-util')
const msg = web3.sha3('hello!');
const sig = web3.eth.sign(web3.eth.accounts[0], msg);
const {v, r, s} = util.fromRpcSig(sig);
const pubKey = util.ecrecover(util.toBuffer(msg), v, r, s);
const addrBuf = util.pubToAddress(pubKey);
const addr = util.bufferToHex(addrBuf);
console.log(web3.eth.accounts[0], addr);发布于 2022-10-05 10:55:52
示例node.js +ethereumjs使用其他方法验证签名
const ethUtil = require("ethereumjs-util");
const inSignature = "0x...."; //user signed message
const message = "hello!";
const msgHex = ethUtil.bufferToHex(Buffer.from(message));
const msgBuffer = ethUtil.toBuffer(msgHex);
const msgHash = ethUtil.hashPersonalMessage(msgBuffer);
const signature = ethUtil.toBuffer(inSignature);
const sigParams = ethUtil.fromRpcSig(signature);
const publicKey = ethUtil.ecrecover(
msgHash,
sigParams.v,
sigParams.r,
sigParams.s
);
const sender = ethUtil.publicToAddress(publicKey);
const addr = ethUtil.bufferToHex(sender);
//now compare addr with user wallet address
if("0x<userWaller>" === addr) console.log("valid");https://ethereum.stackexchange.com/questions/12571
复制相似问题