2

I have a signature created using metamask and the personal_sign RPC method. Now I want to verify this signature in my C# backend. In order to do so I have found the Nethereum library. I have written the below code trying to verify the signature (for now I have used 'test' as the signed message).

public void VerifySignature(string signatureString, string originalMessage)
{
        string msg = "\x19Ethereum Signed Message:\n" + originalMessage.Length + originalMessage;
        byte[] msgHash = new Sha3Keccack().CalculateHash(Encoding.UTF8.GetBytes(msg));

        EthECDSASignature signature = MessageSigner.ExtractEcdsaSignature(signatureString);

        EthECKey key = EthECKey.RecoverFromSignature(signature, msgHash);   
        bool isValid = key.Verify(msgHash, signature);
}

Now the isValid comes back as true. However, if I use key.GetPublicAddress() this address is different than my own public address, so I assume I'm doing something wrong. Can anyone explain to me what, or correct if I'm wrong?

NOTE:

If instead of

EthECKey testKey = EthECKey.RecoverFromSignature(signature, msgHash);

I use

EthECKey testKey = EthECKey.RecoverFromSignature(signature, msgHash, new BigInteger(1));

(I'm using the main network to sign which is chain 1) I get an error saying "recId should be positive", not sure if this is related but I thought it's worth mentioning.

UPDATE:

Managed to fix this by changing the msg string to use "\x19" + "Ethereum ..." instead of "\x19Ethereum ...", \x19E results in a different character, and results in a different message hash.

Tim H
  • 65
  • 8

1 Answers1

4

The Ethereum address and the public key are different. The Ethereum address is the last 20 bytes of the hash of the public key (see https://ethereum.org/en/developers/docs/accounts/ and https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Signer/EthECKey.cs#L201).

Pandapip1
  • 730
  • 5
  • 15