soliditysignaturesigningerc20nethereum

Can't recreate off chain signed message on Solidity


Im using Nethereum on my server to sign a message as follows:

string amount = "10";
string nonce = "1";
string msg1 = "asdasd";
var privateKey = "0x00000privateKey";
var signer1 = new EthereumMessageSigner();

var abiEnconde = new ABIEncode(); 
var byteArray = abiEnconde.GetABIEncodedPacked(msg1,amount, nonce);
var messageHashed = "0x" + Convert.ToHexString(byteArray).ToLower();         
var signature1 = signer1.Sign(byteArray, new EthECKey(privateKey));

signature comes out perfect, the problem comes when I try to recreate the message with its variables in solidity as follows:

function VerifyMessage(bytes memory sig,string memory msg1, string memory amount, string memory nonce) public pure returns (address) {
    (uint8 _v, bytes32 _r, bytes32 _s) = splitSignature(sig);

    bytes memory prefix = "\x19Ethereum Signed Message:\n32";
    bytes32 prefixedHashMessage = keccak256(abi.encodePacked(prefix,msg1,amount,nonce));
    address signer = ecrecover(prefixedHashMessage, _v, _r, _s);
    return signer;
}

The signer is not the wallet that I signed with Nethereum off chain, however, if I try to instead to pass messageHashed from the server instead of recreating the message, it works perfectly, so I think the problem is in the solidity function. Ex.:

bytes32 prefixedHashMessage = keccak256(abi.encodePacked(prefix,HASHED-MSG-FROM-NETHEREUM));

this works fine.


Solution

  • This is how I got it to work

     var abiEnconde = new ABIEncode();
    
     var resultHash = abiEnconde.GetSha3ABIEncodedPacked(
              new ABIValue("address", msg1),
              new ABIValue("uint256", amount),
              new ABIValue("uint256", nonce));
    
     var messageHashed = "0x" + Convert.ToHexString(resultHash).ToLower();
     var signature1 = signer1.Sign(resultHash, new EthECKey(privateKey));
    

    And in solidity:

    function getMessageHash(address add,uint256 amount,uint256 nonce ) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(add,amount,nonce)); 
    }
    

    And to recover the signer>

     bytes memory prefix = "\x19Ethereum Signed Message:\n32";
     bytes32 prefixedHashMessage = keccak256(abi.encodePacked(prefix,getMessageHash(msg1,amount,nonce)));
        
     address signer = ecrecover(prefixedHashMessage, _v, _r, _s);