Why is this public address different for an ethereum signature?

858 Views Asked by At

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.

1

There are 1 best solutions below

0
On

Ethereum addresses and public keys represent two different things. An Ethereum address is the last 20 bytes of the Keccak-256 hash of the corresponding ECDSA (secp256k1) public key.

For more information, see https://ethereum.org/en/developers/docs/accounts/.