Skip to content

Instantly share code, notes, and snippets.

@shrimalmadhur
Last active January 23, 2023 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shrimalmadhur/8ddc6c7e021e2205b4723d2cf866e9ea to your computer and use it in GitHub Desktop.
Save shrimalmadhur/8ddc6c7e021e2205b4723d2cf866e9ea to your computer and use it in GitHub Desktop.
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 message
msg = b"message"
signature = priv.sign(msg).hex() # print hex
print(signature)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment