test_key.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 = pk.blind(encrypted, 4134431) # blind before decrypting
  17. decrypted = rsa.core.decrypt_int(blinded, pk.d, pk.n)
  18. unblinded = pk.unblind(decrypted, 4134431)
  19. self.assertEqual(unblinded, message)
  20. class KeyGenTest(unittest.TestCase):
  21. def test_custom_exponent(self):
  22. priv, pub = rsa.key.newkeys(16, exponent=3)
  23. self.assertEqual(3, priv.e)
  24. self.assertEqual(3, pub.e)
  25. def test_default_exponent(self):
  26. priv, pub = rsa.key.newkeys(16)
  27. self.assertEqual(0x10001, priv.e)
  28. self.assertEqual(0x10001, pub.e)
  29. def test_exponents_coefficient_calculation(self):
  30. pk = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
  31. self.assertEqual(pk.exp1, 55063)
  32. self.assertEqual(pk.exp2, 10095)
  33. self.assertEqual(pk.coef, 50797)
  34. def test_custom_getprime_func(self):
  35. # List of primes to test with, in order [p, q, p, q, ....]
  36. # By starting with two of the same primes, we test that this is
  37. # properly rejected.
  38. primes = [64123, 64123, 64123, 50957, 39317, 33107]
  39. def getprime(_):
  40. return primes.pop(0)
  41. # This exponent will cause two other primes to be generated.
  42. exponent = 136407
  43. (p, q, e, d) = rsa.key.gen_keys(64,
  44. accurate=False,
  45. getprime_func=getprime,
  46. exponent=exponent)
  47. self.assertEqual(39317, p)
  48. self.assertEqual(33107, q)
  49. class HashTest(unittest.TestCase):
  50. """Test hashing of keys"""
  51. def test_hash_possible(self):
  52. priv, pub = rsa.key.newkeys(16)
  53. # This raises a TypeError when hashing isn't possible.
  54. hash(priv)
  55. hash(pub)