|
3 | 3 | # Distributed under the MIT software license, see the accompanying
|
4 | 4 | # file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
5 | 5 |
|
6 |
| -import sys |
7 |
| -import os |
8 |
| -import base64 |
| 6 | +from argparse import ArgumentParser |
| 7 | +from base64 import urlsafe_b64encode |
9 | 8 | from binascii import hexlify
|
| 9 | +from getpass import getpass |
| 10 | +from os import urandom |
| 11 | + |
10 | 12 | import hmac
|
11 | 13 |
|
12 | 14 | def generate_salt(size):
|
13 | 15 | """Create size byte hex salt"""
|
14 |
| - return hexlify(os.urandom(size)).decode() |
| 16 | + return hexlify(urandom(size)).decode() |
15 | 17 |
|
16 | 18 | def generate_password():
|
17 | 19 | """Create 32 byte b64 password"""
|
18 |
| - return base64.urlsafe_b64encode(os.urandom(32)).decode('utf-8') |
| 20 | + return urlsafe_b64encode(urandom(32)).decode('utf-8') |
19 | 21 |
|
20 | 22 | def password_to_hmac(salt, password):
|
21 | 23 | m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256')
|
22 | 24 | return m.hexdigest()
|
23 | 25 |
|
24 | 26 | def main():
|
25 |
| - if len(sys.argv) < 2: |
26 |
| - sys.stderr.write('Please include username (and an optional password, will generate one if not provided) as an argument.\n') |
27 |
| - sys.exit(0) |
| 27 | + parser = ArgumentParser(description='Create login credentials for a JSON-RPC user') |
| 28 | + parser.add_argument('username', help='the username for authentication') |
| 29 | + parser.add_argument('password', help='leave empty to generate a random password or specify "-" to prompt for password', nargs='?') |
| 30 | + args = parser.parse_args() |
28 | 31 |
|
29 |
| - username = sys.argv[1] |
| 32 | + if not args.password: |
| 33 | + args.password = generate_password() |
| 34 | + elif args.password == '-': |
| 35 | + args.password = getpass() |
30 | 36 |
|
31 | 37 | # Create 16 byte hex salt
|
32 | 38 | salt = generate_salt(16)
|
33 |
| - if len(sys.argv) > 2: |
34 |
| - password = sys.argv[2] |
35 |
| - else: |
36 |
| - password = generate_password() |
37 |
| - password_hmac = password_to_hmac(salt, password) |
| 39 | + password_hmac = password_to_hmac(salt, args.password) |
38 | 40 |
|
39 | 41 | print('String to be appended to bitcoin.conf:')
|
40 |
| - print('rpcauth={0}:{1}${2}'.format(username, salt, password_hmac)) |
41 |
| - print('Your password:\n{0}'.format(password)) |
| 42 | + print('rpcauth={0}:{1}${2}'.format(args.username, salt, password_hmac)) |
| 43 | + print('Your password:\n{0}'.format(args.password)) |
42 | 44 |
|
43 | 45 | if __name__ == '__main__':
|
44 | 46 | main()
|
0 commit comments