2017-10-11 15:21:07 -04:00
|
|
|
import unittest
|
|
|
|
|
|
2020-05-28 17:18:13 +02:00
|
|
|
from diffie_hellman import private_key, public_key, secret
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2020-10-15 12:46:24 -04:00
|
|
|
# Tests adapted from `problem-specifications//canonical-data.json`
|
2018-06-11 09:51:01 -04:00
|
|
|
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2020-05-28 17:18:13 +02:00
|
|
|
class DiffieHellmanTest(unittest.TestCase):
|
2020-10-15 12:47:31 -04:00
|
|
|
def test_private_key_is_greater_than_1_and_less_than_p(self):
|
2017-10-11 15:21:07 -04:00
|
|
|
primes = [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
|
2020-05-28 17:18:13 +02:00
|
|
|
for p in primes:
|
|
|
|
|
self.assertTrue(1 < private_key(p) < p)
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2018-06-11 09:51:01 -04:00
|
|
|
def test_private_key_is_random(self):
|
2020-05-28 17:18:13 +02:00
|
|
|
"""
|
|
|
|
|
Can fail due to randomness, but most likely will not,
|
|
|
|
|
due to pseudo-randomness and the large number chosen
|
|
|
|
|
"""
|
2017-10-11 15:21:07 -04:00
|
|
|
p = 2147483647
|
2020-05-28 17:18:13 +02:00
|
|
|
private_keys = [private_key(p) for _ in range(5)]
|
2018-06-11 09:51:01 -04:00
|
|
|
self.assertEqual(len(set(private_keys)), len(private_keys))
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2018-06-11 09:51:01 -04:00
|
|
|
def test_can_calculate_public_key_using_private_key(self):
|
2017-10-11 15:21:07 -04:00
|
|
|
p = 23
|
|
|
|
|
g = 5
|
2020-05-28 17:18:13 +02:00
|
|
|
private_key = 6
|
|
|
|
|
self.assertEqual(8, public_key(p, g, private_key))
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2018-06-11 09:51:01 -04:00
|
|
|
def test_can_calculate_secret_using_other_party_s_public_key(self):
|
2017-10-11 15:21:07 -04:00
|
|
|
p = 23
|
2020-05-28 17:18:13 +02:00
|
|
|
their_public_key = 19
|
|
|
|
|
my_private_key = 6
|
|
|
|
|
self.assertEqual(2, secret(p, their_public_key, my_private_key))
|
2017-10-11 15:21:07 -04:00
|
|
|
|
2018-06-11 09:51:01 -04:00
|
|
|
def test_key_exchange(self):
|
2017-10-11 15:21:07 -04:00
|
|
|
p = 23
|
|
|
|
|
g = 5
|
2020-05-28 17:18:13 +02:00
|
|
|
alice_private_key = private_key(p)
|
|
|
|
|
bob_private_key = private_key(p)
|
|
|
|
|
alice_public_key = public_key(p, g, alice_private_key)
|
|
|
|
|
bob_public_key = public_key(p, g, bob_private_key)
|
|
|
|
|
secret_a = secret(p, bob_public_key, alice_private_key)
|
|
|
|
|
secret_b = secret(p, alice_public_key, bob_private_key)
|
|
|
|
|
self.assertTrue(secret_a == secret_b)
|
2017-10-11 15:21:07 -04:00
|
|
|
|
|
|
|
|
|
2020-05-28 17:18:13 +02:00
|
|
|
if __name__ == "__main__":
|
2017-10-11 15:21:07 -04:00
|
|
|
unittest.main()
|