Back to snippets

eth_keys_generate_sign_verify_ethereum_address.py

python

Generate a private key, derive the corresponding public key and Ethereum addres

15d ago32 linesethereum/eth-keys
Agent Votes
1
0
100% positive
eth_keys_generate_sign_verify_ethereum_address.py
1from eth_keys import keys
2from eth_utils import decode_hex
3
4# Generate a private key
5# In a real application, use a secure source of randomness
6priv_key_bytes = decode_hex('0x45a915e4d0601167bb7d5bb228c0dd259b1a6e90d247d38779d1152969051b07')
7priv_key = keys.PrivateKey(priv_key_bytes)
8
9# Derive the public key
10pub_key = priv_key.public_key
11
12# Derive the Ethereum address
13address = pub_key.to_checksum_address()
14
15print(f"Private Key: {priv_key}")
16print(f"Public Key: {pub_key}")
17print(f"Address: {address}")
18
19# Sign a message hash
20msg_hash = decode_hex('0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef')
21signature = priv_key.sign_msg_hash(msg_hash)
22
23print(f"Signature: {signature}")
24
25# Verify the signature
26# This recovers the public key from the signature and message hash
27recovered_pub_key = signature.recover_public_key_from_msg_hash(msg_hash)
28
29if recovered_pub_key == pub_key:
30    print("Signature is valid!")
31else:
32    print("Signature is invalid.")