我正在尝试创建一个C# webservice后端API,它处理在步骤5中找到的代码逻辑:https://www.toptal.com/ethereum/one-click-login-flows-a-metamask-tutorial
他们的代码如下所示:
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。
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#代码以使其返回为真,我需要做什么?
发布于 2020-09-06 21:32:53
// ("\x19Ethereum") != ("\x19" + "Ethereum")
var message = Encoding.UTF8.GetBytes("\x19" + "Ethereum Signed Message:\n" + terms.Length + terms);发布于 2021-08-05 20:46:33
对于到达这里的其他人,有一个build in函数,负责编码、散列、验证和构建字符串:
var recoveredAddress = signer.EncodeUTF8AndEcRecover(message, signature);只需注意,恢复的地址是混合大小写(构建在校验和中),所以IgnoreCase比较或小写两者都是。
https://ethereum.stackexchange.com/questions/87250
复制相似问题