首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从ecrecover中获取错误的地址

从ecrecover中获取错误的地址
EN

Ethereum用户
提问于 2017-03-01 11:54:21
回答 1查看 3.7K关注 0票数 16

当我使用下面的代码对字符串进行签名时,我会得到一个与我签名的地址不同的地址。对于不同的字符串,返回的地址不同。

代码语言:javascript
复制
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实现.关于一个可能相关的错误。不过,这些评论表明,这应该是无害的。

EN

回答 1

Ethereum用户

回答已采纳

发布于 2017-03-02 19:14:17

Geth在web3.eth.sign中的siginig消息之前添加前缀(参见JSON-中华人民共和国规范)。没有这一点,就可以欺骗用户签名事务(更多的这里)。

因此,使用web3.eth.sign签名消息和用ethereumjs-util.ecrecover或(Solidity's ecrecover)恢复地址的正确代码应该显式地添加前缀。

代码语言:javascript
复制
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中签名之前没有前缀消息。

票数 12
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/12621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档