Ethereum: Using Python: create a private key of my choosing, then generate public key and address
Ethereum: Verifying Private Key and Generating Public Address with Python
In this article, we will explore how to use the official Ethereum library for Python to verify a private key and generate a public address. We will also demonstrate how to compress the public key in hexadecimal format.
Prerequisites
To run this example, you need to have Python installed on your machine. You can download it from the official Python website: <
For this example, we will use the eth library, which is a simple and easy-to-use Bitcoin-related library for Python.
Install the eth Library
Run the following command in your terminal to install the eth library:
pip install ethlib
Verify Private Key with Python
import ethlib

Choose a private key
private_key = "your_private_key_hex_here"
try:
Verify the private key
private_key_obj = ethlib.EthAccount.fromPrivateKey(private_key.encode())
print("Private Key Verified:")
print(private_key_obj.publicKey.hex())
except ValueError as e:
print(f"Error: {e}")
In this example, we first import the ethlib library. We then create an instance of the EthAccount class using our private key in hexadecimal format (replace “your_private_key_hex_here” with your actual private key). The fromPrivateKey method verifies the private key and returns an account object.
The publicKey.hex() attribute returns a compressed hexadecimal representation of the public key. We print this value to verify that the verification was successful.
Generate Public Address
import ethlib
Choose the private key
private_key = "your_private_key_hex_here"
try:
Generate a new public address
public_address_obj = ethlib.EthAccount.fromPrivateKey(private_key.encode())
print("Public Address:")
print(public_address_obj.publicKey.hex())
except ValueError as e:
print(f"Error: {e}")
In this example, we create an instance of the EthAccount class using our private key. We then generate a new public address for the account using the fromPrivateKey method.
The publicKey.hex() attribute returns a compressed hexadecimal representation of the public key. We print this value to get the expected 1Btc address (replace “your_private_key_hex_here” with your actual private key).
Tips and Variations
- Make sure to replace the placeholder values in the code with your own private key.
- To generate a new private key, you can use the
createNewKeymethod of theEthAccountclass.
- You can also use the
printAddressattribute of theEthAccountobject to get the public address as a string.
Conclusion
In this article, we have explored how to verify a private key using Python and generate a public address. We have demonstrated how to compress the public key in hexadecimal format using the fromPrivateKey method. With this library, you can easily work with Ethereum accounts and generate new keys or addresses as needed.

Leave a Reply
Want to join the discussion?Feel free to contribute!