[Ethereum] web3py: get public key from private key (without prior transaction)

private-keypublic-keyweb3.py

Is there a way to get the public key from a private key with web3.py? I know I could get it by checking a transaction signed by that key but that's not working for me in this example.

It should be accessible somehow as the address is derived from it. So there must be an internal way within web3.py to access it.

Unfortunately there is no information on it in the docs and all I found was this solution for web3j which isn't portable to web3.py.

Best Answer

If you want convert private key to public key and not address, then I would recommend using eth-keys library. It is in the dependencies of eth-account library, which is in the dependencies of web3py.

Private key, used for account generation, consists of 64 hexadecimal characters (32 bytes total). So, if you have 32-bytes private key, then public key can be acquired with the following code:

>>> from eth_keys import keys
>>> pk = keys.PrivateKey(your_32bytes_private_key)
>>> print(pk.public_key)

If your private key is a string of 64 characters, then it can be converted to 32-bytes private key with the following code:

>>> import codecs
>>> decoder = codecs.getdecoder("hex_codec")
>>> private_key_bytes = decoder(private_key_str)
Related Topic