web3dart icon indicating copy to clipboard operation
web3dart copied to clipboard

How to verify a signature/signed message? Example?

Open oliverbytes opened this issue 2 years ago • 1 comments

I'm new to Web3 and hope to find an example how to sign and verify messages. Anyone care to share please? Will appreciate any help.

oliverbytes avatar May 01 '22 22:05 oliverbytes

simple 'personal_message` flutter


      final address = EthereumAddress.fromHex(account);
      String message = "buyer${sellerAdress.toLowerCase()}$orderId";
      final data = await connector.sendCustomRequest(
          method: "personal_sign", params: [message, address.hex, message]);

solidity

       import "@openzeppelin/contracts/utils/Strings.sol";
      using Decryption for bytes32;


    function _veryfiPayment(
        uint64 _orderId,
        address _signer,
        address _receiver,
        bytes memory sign
    ) internal view returns (bool) {
        bytes memory _hash = abi.encodePacked(
            "buyer",
            Strings.toHexString(uint160(_receiver), 20),
            Strings.toString(_orderId)
        );
        bytes32 hash = keccak256(
            abi.encodePacked(
                "\x19Ethereum Signed Message:\n",
                Strings.toString(_hash.length),
                _hash
            )
        );
        address signerAddress = hash.recoverSignedMessage(sign);
        return signerAddress == _signer;
    }
}

library Decryption {
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        if (
            uint256(s) >
            0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
        ) {
            return address(0);
        }
        if (v != 27 && v != 28) {
            return address(0);
        }
        address signer = ecrecover(hash, v, r, s);
        return signer;
    }

    function recoverSignedMessage(bytes32 hash, bytes memory message)
        internal
        pure
        returns (address)
    {
        require(message.length == 65);
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := mload(add(message, 0x20))
            s := mload(add(message, 0x40))
            v := byte(0, mload(add(message, 0x60)))
        }
        return recover(hash, v, r, s);
    }
}


for verify in flutter u can use Dart-ECDSA package

mrtnetwork avatar Jun 15 '22 08:06 mrtnetwork