Skip to content

Instantly share code, notes, and snippets.

@shrimalmadhur
Last active Apr 15, 2022
Embed
What would you like to do?
Derive public key from private key
# Reference - https://stackoverflow.com/a/53488466
# pre req with python3
# pip3 install ecdsa
# pip3 install pysha3 # sha3 won't work
from ecdsa import SigningKey, SECP256k1
import sha3, random, binascii
private_key = "<some private key in hex string>"
private_key = bytes(private_key, 'utf-8')
private_key = binascii.unhexlify(private_key)
priv = SigningKey.from_string(private_key, curve=SECP256k1)
pub = priv.get_verifying_key().to_string() # This will be an uncompressed key
pub_compressed = priv.get_verifying_key().to_string('compressed') # This will be an compressed key
keccak = sha3.keccak_256()
keccak.update(pub)
address = keccak.hexdigest()[24:]
print(address, priv.to_string().hex())
print(pub.hex()) # uncompressed key
print(pub_compressed.hex()) # compressed key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment