test_key.py 2.6 KB

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