Sunday, December 22, 2024

cryptography – Tips on how to convert non-public key to ethereum handle utilizing python

That is my code:

from eth_keys import keys
from eth_utils import decode_hex, encode_hex, keccak

def private_key_to_address(private_key_hex):
    # Make sure the non-public key's a legitimate hex string
    if private_key_hex.startswith('0x'):
        private_key_hex = private_key_hex[2:]
    
    # Convert the hex non-public key to bytes
    private_key_bytes = bytes.fromhex(private_key_hex)
    
    # Create a PrivateKey object
    private_key = keys.PrivateKey(private_key_bytes)
    
    # Derive the general public key from the non-public key
    public_key = private_key.public_key
    
    # Get the general public key bytes and skip the primary byte (which is 0x04)
    public_key_bytes = public_key.to_bytes()[1:]
    
    # Compute the Keccak-256 hash of the general public key bytes
    keccak_hash = keccak(public_key_bytes)
    
    # The Ethereum handle is the final 20 bytes of this hash
    address_bytes = keccak_hash[-20:]
    
    # Convert the handle bytes to a hexadecimal string and prepend '0x'
    handle="0x" + address_bytes.hex()
    return handle

# Instance utilization
private_key_hex = '0x0000000000000000000000000000000000000000000000000000000000000001'
eth_address = private_key_to_address(private_key_hex)
print("Ethereum Handle:", eth_address)

I’m going to transform 0x0000000000000000000000000000000000000000000000000000000000000001 to Ethereum Handle. So, desired output is

0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf

However getting

0x6579c588be2026d866231cccc364881cc1219c56

The place is the mistaken in my code?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles