首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EcRecover签名消息与PublicAddress不匹配

EcRecover签名消息与PublicAddress不匹配
EN

Ethereum用户
提问于 2020-09-06 19:45:29
回答 2查看 814关注 0票数 2

我正在尝试创建一个C# webservice后端API,它处理在步骤5中找到的代码逻辑:https://www.toptal.com/ethereum/one-click-login-flows-a-metamask-tutorial

他们的代码如下所示:

代码语言:javascript
复制
User.findOne({ where: { publicAddress } })
  // --snip--
  .then(user => {
    const msg = `I am signing my one-time nonce: ${user.nonce}`;

    // We now are in possession of msg, publicAddress and signature. We
    // can perform an elliptic curve signature verification with ecrecover
    const msgBuffer = ethUtil.toBuffer(msg);
    const msgHash = ethUtil.hashPersonalMessage(msgBuffer);
    const signatureBuffer = ethUtil.toBuffer(signature);
    const signatureParams = ethUtil.fromRpcSig(signatureBuffer);
    const publicKey = ethUtil.ecrecover(
      msgHash,
      signatureParams.v,
      signatureParams.r,
      signatureParams.s
    );
    const addressBuffer = ethUtil.publicToAddress(publicKey);
    const address = ethUtil.bufferToHex(addressBuffer);

    // The signature verification is successful if the address found with
    // ecrecover matches the initial publicAddress
    if (address.toLowerCase() === publicAddress.toLowerCase()) {
      return user;
    } else {
      return res
        .status(401)
        .send({ error: 'Signature verification failed' });
    }
  })

我的代码如下所示。但它总是返回假的。我最初的猜测是,“消息”格式在某种程度上是不正确的。我已经看到了其他示例,不包括"\x19“部分,而是删除它并包含它都返回false。

代码语言:javascript
复制
public static bool AccountSignerIsValid(string signature, string publicAddress)
{
    var nonce = "12345678";
    var terms = "Please sign to log in: " + nonce;
    var message = Encoding.UTF8.GetBytes("\x19Ethereum Signed Message:\n" + terms.Length + terms);
    var hash = (new Sha3Keccack()).CalculateHash(message.ToArray());

    var signer = new Nethereum.Signer.MessageSigner();
    var account = signer.EcRecover(hash, signature);

    return (account.ToLower().Equals(publicAddress.ToLower()));
}

要更改C#代码以使其返回为真,我需要做什么?

EN

回答 2

Ethereum用户

发布于 2020-09-06 21:32:53

代码语言:javascript
复制
//  ("\x19Ethereum")  !=  ("\x19" + "Ethereum")
var message = Encoding.UTF8.GetBytes("\x19" + "Ethereum Signed Message:\n" + terms.Length + terms);
票数 1
EN

Ethereum用户

发布于 2021-08-05 20:46:33

对于到达这里的其他人,有一个build in函数,负责编码、散列、验证和构建字符串:

代码语言:javascript
复制
var recoveredAddress = signer.EncodeUTF8AndEcRecover(message, signature);

只需注意,恢复的地址是混合大小写(构建在校验和中),所以IgnoreCase比较或小写两者都是。

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

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

复制
相关文章

相似问题

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