• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
2Some tests for the rsa/key.py file.
3"""
4
5import unittest
6
7import rsa.key
8import rsa.core
9
10
11class BlindingTest(unittest.TestCase):
12    def test_blinding(self):
13        """Test blinding and unblinding.
14
15        This is basically the doctest of the PrivateKey.blind method, but then
16        implemented as unittest to allow running on different Python versions.
17        """
18
19        pk = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
20
21        message = 12345
22        encrypted = rsa.core.encrypt_int(message, pk.e, pk.n)
23
24        blinded_1 = pk.blind(encrypted)  # blind before decrypting
25        decrypted = rsa.core.decrypt_int(blinded_1, pk.d, pk.n)
26        unblinded_1 = pk.unblind(decrypted)
27
28        self.assertEqual(unblinded_1, message)
29
30        # Re-blinding should use a different blinding factor.
31        blinded_2 = pk.blind(encrypted)  # blind before decrypting
32        self.assertNotEqual(blinded_1, blinded_2)
33
34        # The unblinding should still work, though.
35        decrypted = rsa.core.decrypt_int(blinded_2, pk.d, pk.n)
36        unblinded_2 = pk.unblind(decrypted)
37        self.assertEqual(unblinded_2, message)
38
39
40class KeyGenTest(unittest.TestCase):
41    def test_custom_exponent(self):
42        priv, pub = rsa.key.newkeys(16, exponent=3)
43
44        self.assertEqual(3, priv.e)
45        self.assertEqual(3, pub.e)
46
47    def test_default_exponent(self):
48        priv, pub = rsa.key.newkeys(16)
49
50        self.assertEqual(0x10001, priv.e)
51        self.assertEqual(0x10001, pub.e)
52
53    def test_exponents_coefficient_calculation(self):
54        pk = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
55
56        self.assertEqual(pk.exp1, 55063)
57        self.assertEqual(pk.exp2, 10095)
58        self.assertEqual(pk.coef, 50797)
59
60    def test_custom_getprime_func(self):
61        # List of primes to test with, in order [p, q, p, q, ....]
62        # By starting with two of the same primes, we test that this is
63        # properly rejected.
64        primes = [64123, 64123, 64123, 50957, 39317, 33107]
65
66        def getprime(_):
67            return primes.pop(0)
68
69        # This exponent will cause two other primes to be generated.
70        exponent = 136407
71
72        (p, q, e, d) = rsa.key.gen_keys(64,
73                                        accurate=False,
74                                        getprime_func=getprime,
75                                        exponent=exponent)
76        self.assertEqual(39317, p)
77        self.assertEqual(33107, q)
78
79
80class HashTest(unittest.TestCase):
81    """Test hashing of keys"""
82
83    def test_hash_possible(self):
84        priv, pub = rsa.key.newkeys(16)
85
86        # This raises a TypeError when hashing isn't possible.
87        hash(priv)
88        hash(pub)
89