首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Metamask签署消息,并使用ethereumjs utils进行验证。

使用Metamask签署消息,并使用ethereumjs utils进行验证。
EN

Ethereum用户
提问于 2017-02-09 14:51:04
回答 1查看 6.4K关注 0票数 7

客户端:

代码语言:javascript
复制
web3.eth.sign(address, hash); // generates signature

服务器端:

代码语言:javascript
复制
const ethutils = require('ethereumjs-util');

const extractAddress = function(signature, hash){ //signature and hash from the client side
  const o = ethutils.fromRpcSig(signature);
  const hashBuffer = ethutils.toBuffer(hash);
  const publicKeyBuffer = ethutils.ecrecover(hashBuffer, o.v, o.r, o.s);
  const publicKeyHex = ethutils.bufferToHex(publicKeyBuffer);
  const addressBuffer = ethutils.pubToAddress(publicKeyHex);
  const addressHex = ethutils.bufferToHex(addressBuffer);
  return addressHex;
}

地址不匹配。这段代码在几个月前就起作用了。

相关讨论https://github.com/ethereumjs/ethereumjs-util/pull/67

EN

回答 1

Ethereum用户

发布于 2018-04-01 09:03:32

老问题,但这对我有用。我使用的是web3@0.20.3。

1.与personal_sign (推荐)

客户端:

代码语言:javascript
复制
web3.personal.sign(web3.fromUtf8("dinosaur"), web3.eth.coinbase, console.log);

服务器端:

代码语言:javascript
复制
const msg = 'dinosaur';

const msgBuffer = ethereumJsUtil.toBuffer(msg);
const msgHash = ethereumJsUtil.hashPersonalMessage(msgBuffer);
const signatureBuffer = ethereumJsUtil.toBuffer(signature);
const signatureParams = ethereumJsUtil.fromRpcSig(signatureBuffer);
const publicKey = ethereumJsUtil.ecrecover(
  msgHash,
  signatureParams.v,
  signatureParams.r,
  signatureParams.s
);
const addressBuffer = ethereumJsUtil.publicToAddress(publicKey);
const address = ethereumJsUtil.bufferToHex(addressBuffer);

console.log(address); // Prints my initial web3.eth.coinbase

2.使用eth_sign

客户端:

代码语言:javascript
复制
web3.eth.sign(web3.eth.coinbase, web3.sha3("dinosaur"), console.log);

服务器端:

代码语言:javascript
复制
const msg = 'dinosaur';

const msgHash = ethereumJsUtil.sha3(msg);
// The rest is the same as above
const signatureBuffer = ethereumJsUtil.toBuffer(signature);
const signatureParams = ethereumJsUtil.fromRpcSig(signatureBuffer);
const publicKey = ethereumJsUtil.ecrecover(
  msgHash,
  signatureParams.v,
  signatureParams.r,
  signatureParams.s
);
const addressBuffer = ethereumJsUtil.publicToAddress(publicKey);
const address = ethereumJsUtil.bufferToHex(addressBuffer);

console.log(address); // Prints my initial web3.eth.coinbase
票数 10
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

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

复制
相关文章

相似问题

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