3

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
MUHASIN BABU
  • 313
  • 3
  • 9

2 Answers2

4

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

carver
  • 2,229
  • 12
  • 28
  • When i use this `web3.eth.account.create(extra_entropy)` , it doesn't create new account in my node – MUHASIN BABU Jun 25 '18 at 03:08
  • 1
    That's correct. But you can generate a geth-style keyfile that most nodes can import, with `w3.eth.account.encrypt()`. See http://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.encrypt for parameters and example. – carver Jun 25 '18 at 18:08
0

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rouhollah Joveini
  • 158
  • 1
  • 3
  • 14