how to verify ethereum message in python

To verify an Ethereum message in Python, you can use the cryptography library to handle the cryptographic operations and the web3 library to interact with an Ethereum node.

Here's an example code snippet:

main.py
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey, EllipticCurveSignature
from cryptography.hazmat.backends import default_backend
from web3 import Web3, HTTPProvider

message = "Hello, Ethereum!"
signature = "0x9a98f80a46c601d879a4ecbfcf6efd823fbe6d4ee6efce913f6215379efa3c3d3d853f37db16612610ab0a34a17d18581d93570928c9b7bf9e2612d6917d83871b"
address = "0x8a5a5e3Dbb9770f23160Ea82Ba45a0C082E775eB"

# Connect to a local Ethereum node
w3 = Web3(HTTPProvider('http://localhost:8545'))

# Get the public key associated with the address
public_key = w3.eth.account.recover_message(message, signature=signature)

# Deserialize the public key string into a `cryptography` public key object
public_key_obj = serialization.load_der_public_key(bytes.fromhex(public_key[2:]), backend=default_backend())

# Deserialize the signature string into a `cryptography` signature object
signature_obj = EllipticCurveSignature.from_hex(signature)

# Verify the signature
try:
    public_key_obj.verify(signature_obj, message.encode('utf-8'), hashes.SHA256())
    print(f"Message verified! Signature is valid for address: {address}")
except Exception as e:
    print(f"Message verification failed: {e}")
1279 chars
28 lines

This code connects to a local Ethereum node, specifies the original message and signature, and verifies the signature by loading the public key and signature objects using cryptography. If the verification succeeds, it prints a message indicating that the message is valid for the specified Ethereum address.

gistlibby LogSnag