1#!/usr/bin/env python3
2# Copyright (c) 2015-2018 The Bitcoin Core developers
3# Distributed under the MIT software license, see the accompanying
4# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5"""Test share/rpcauth/rpcauth.py
6"""
7import base64
8import configparser
9import hmac
10import importlib
11import os
12import sys
13import unittest
14
15class TestRPCAuth(unittest.TestCase):
16    def setUp(self):
17        config = configparser.ConfigParser()
18        config_path = os.path.abspath(
19            os.path.join(os.sep, os.path.abspath(os.path.dirname(__file__)),
20            "../config.ini"))
21        with open(config_path, encoding="utf8") as config_file:
22            config.read_file(config_file)
23        sys.path.insert(0, os.path.dirname(config['environment']['RPCAUTH']))
24        self.rpcauth = importlib.import_module('rpcauth')
25
26    def test_generate_salt(self):
27        for i in range(16, 32 + 1):
28            self.assertEqual(len(self.rpcauth.generate_salt(i)), i * 2)
29
30    def test_generate_password(self):
31        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)
35
36    def test_check_password_hmac(self):
37        salt = self.rpcauth.generate_salt(16)
38        password = self.rpcauth.generate_password()
39        password_hmac = self.rpcauth.password_to_hmac(salt, password)
40
41        m = hmac.new(bytearray(salt, 'utf-8'),
42            bytearray(password, 'utf-8'), 'SHA256')
43        expected_password_hmac = m.hexdigest()
44
45        self.assertEqual(expected_password_hmac, password_hmac)
46
47if __name__ == '__main__':
48    unittest.main()
49