Skip to content

Commit e4e1790

Browse files
committed
Modernize rpcauth.py and its tests
1 parent 2c1fe27 commit e4e1790

File tree

2 files changed

+11
-14
lines changed

2 files changed

+11
-14
lines changed

Diff for: share/rpcauth/rpcauth.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,20 @@
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
55

66
from argparse import ArgumentParser
7-
from base64 import urlsafe_b64encode
87
from getpass import getpass
9-
from os import urandom
10-
8+
from secrets import token_hex, token_urlsafe
119
import hmac
1210

1311
def generate_salt(size):
1412
"""Create size byte hex salt"""
15-
return urandom(size).hex()
13+
return token_hex(size)
1614

1715
def generate_password():
1816
"""Create 32 byte b64 password"""
19-
return urlsafe_b64encode(urandom(32)).decode('utf-8')
17+
return token_urlsafe(32)
2018

2119
def password_to_hmac(salt, password):
22-
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256')
20+
m = hmac.new(salt.encode('utf-8'), password.encode('utf-8'), 'SHA256')
2321
return m.hexdigest()
2422

2523
def main():
@@ -38,8 +36,8 @@ def main():
3836
password_hmac = password_to_hmac(salt, args.password)
3937

4038
print('String to be appended to bitcoin.conf:')
41-
print('rpcauth={0}:{1}${2}'.format(args.username, salt, password_hmac))
42-
print('Your password:\n{0}'.format(args.password))
39+
print(f'rpcauth={args.username}:{salt}${password_hmac}')
40+
print(f'Your password:\n{args.password}')
4341

4442
if __name__ == '__main__':
4543
main()

Diff for: test/util/rpcauth-test.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
55
"""Test share/rpcauth/rpcauth.py
66
"""
7-
import base64
7+
import re
88
import configparser
99
import hmac
1010
import importlib
@@ -28,18 +28,17 @@ def test_generate_salt(self):
2828
self.assertEqual(len(self.rpcauth.generate_salt(i)), i * 2)
2929

3030
def test_generate_password(self):
31+
"""Test that generated passwords only consist of urlsafe characters."""
32+
r = re.compile(r"[0-9a-zA-Z_-]*")
3133
password = self.rpcauth.generate_password()
32-
expected_password = base64.urlsafe_b64encode(
33-
base64.urlsafe_b64decode(password)).decode('utf-8')
34-
self.assertEqual(expected_password, password)
34+
self.assertTrue(r.fullmatch(password))
3535

3636
def test_check_password_hmac(self):
3737
salt = self.rpcauth.generate_salt(16)
3838
password = self.rpcauth.generate_password()
3939
password_hmac = self.rpcauth.password_to_hmac(salt, password)
4040

41-
m = hmac.new(bytearray(salt, 'utf-8'),
42-
bytearray(password, 'utf-8'), 'SHA256')
41+
m = hmac.new(salt.encode('utf-8'), password.encode('utf-8'), 'SHA256')
4342
expected_password_hmac = m.hexdigest()
4443

4544
self.assertEqual(expected_password_hmac, password_hmac)

0 commit comments

Comments
 (0)