当我使用下面的代码对字符串进行签名时,我会得到一个与我签名的地址不同的地址。对于不同的字符串,返回的地址不同。
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);我把答案中的代码从我前面提出的一个问题中提取出来,从ethereumjs使用erecover获得一个地址。
我在这里问了一个问题:没有编译Secp256k1绑定.将使用纯JS实现.关于一个可能相关的错误。不过,这些评论表明,这应该是无害的。
发布于 2017-03-02 19:14:17
Geth在web3.eth.sign中的siginig消息之前添加前缀(参见JSON-中华人民共和国规范)。没有这一点,就可以欺骗用户签名事务(更多的这里)。
因此,使用web3.eth.sign签名消息和用ethereumjs-util.ecrecover或(Solidity's ecrecover)恢复地址的正确代码应该显式地添加前缀。
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);与ethereumjs-testrpc存在误导性的不一致性,因为它在web3.eth.sign中签名之前没有前缀消息。
https://ethereum.stackexchange.com/questions/12621
复制相似问题