Reputation: 343
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?
Upvotes: 3
Views: 4781
Reputation: 158
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)
Upvotes: 0
Reputation: 2349
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:
w3.eth.account.create(extra_entropy)
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
Upvotes: 4