/
key.py
67 lines (58 loc) · 2.27 KB
/
key.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import ethereum.utils as eth
import ethereum.tools.keys as ethkeys
import os
import sys
import logging
import json
import getpass
import secrets
def create_private_key(output_file):
password = ''
password2 = ' '
while password != password2:
password = getpass.getpass('Type the password: ')
password2 = getpass.getpass('Retype the password: ')
priv = secrets.randbits(256)
logging.info('Private key succesfully generated.')
addr = eth.privtoaddr(priv)
logging.info("The generated address is '{}'".format('0x' + eth.encode_hex(
addr)))
store_private_key(priv, password, output_file)
def store_private_key(key, password, output_file):
bkey = eth.normalize_key(key)
keystore_json = ethkeys.make_keystore_json(bkey, password, kdf='pbkdf2',
cipher='aes-128-ctr')
keystore_json['id'] = keystore_json['id'].decode('utf8')
logging.debug(keystore_json)
if os.path.isdir(os.path.dirname(output_file)):
if not os.path.isfile(output_file):
with open(output_file, 'w') as f:
json.dump(keystore_json, f)
logging.info("Private key succesfully stored on file "
"'{}'.".format(output_file))
else:
logging.error('Keystore file already present! Aborting.')
sys.exit(1)
else:
logging.error("Parent directory of keystore file doesn't exist. "
"Aborting")
sys.exit(1)
def retrieve_private_key(password, key_file):
if os.path.isfile(key_file):
with open(key_file) as f:
try:
keystore_json = json.load(f)
keystore_json['id'] = keystore_json['id']
key = ethkeys.decode_keystore_json(keystore_json, password)
if not key:
raise Exception
return key
except Exception:
logging.error('Error retrieving private key.')
sys.exit(1)
else:
logging.error("Keystore file '{}' inexistent.".format(key_file))
sys.exit(1)
def get_private_key(key_file):
password = getpass.getpass('Please enter the private key password: ')
return retrieve_private_key(password, key_file)