Access private key after personal.newAccount in web3.py

Question:

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?

Asked By: MUHASIN BABU

||

Answers:

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

Answered By: carver

Assuming you have been activated personal rpc of your geth, to do this programatically without hardcoding the keystore file directory path in python, do the following:

from web3 import Web3
import eth_keys
from eth_account import account

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1'))
address = '0x...'
password = 'password'

wallets_list = w3.geth.personal.list_wallets()
keyfile_path = (wallets_list[list(i['accounts'][0]['address'] for i in wallets_list).index(address)]['url']).replace("keystore://", "").replace("\", "/")
keyfile = open(keyfile_path)
keyfile_contents = keyfile.read()
keyfile.close()
private_key = eth_keys.keys.PrivateKey(account.Account.decrypt(keyfile_contents, password))
public_key = private_key.public_key

private_key_str = str(private_key)
public_key_str = str(public_key)
Answered By: Rouhollah Joveini
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.