Search code examples
pythonpython-3.xethereumweb3py

Access private key after personal.newAccount in web3.py


I have created an Ethereum account using web3.py in python 3.6:

web3.personal.newAccount('password')

How do I access the private key for that account?


Solution

  • When you create an account on your node (which w3.personal.newAccount() does), the node hosts the private key; direct access to it is not intended.

    If you must have local access to the private key, you can either:

    If the node is geth, extracting the key looks like:

    with open('~/.ethereum/keystore/UTC--...4909639D2D17A3F753ce7d93fa0b9aB12E') as keyfile:
        encrypted_key = keyfile.read()
        private_key = w3.eth.account.decrypt(encrypted_key, 'correcthorsebatterystaple')
    

    Security tip -- Do not save the key or password anywhere, especially into a shared source file