test_RSA.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # -*- coding: utf-8 -*-
  2. #
  3. # SelfTest/PublicKey/test_RSA.py: Self-test for the RSA primitive
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. """Self-test suite for Cryptodome.PublicKey.RSA"""
  25. __revision__ = "$Id$"
  26. import os
  27. import pickle
  28. from pickle import PicklingError
  29. from Cryptodome.Util.py3compat import *
  30. import unittest
  31. from Cryptodome.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
  32. class RSATest(unittest.TestCase):
  33. # Test vectors from "RSA-OAEP and RSA-PSS test vectors (.zip file)"
  34. # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip
  35. # See RSADSI's PKCS#1 page at
  36. # http://www.rsa.com/rsalabs/node.asp?id=2125
  37. # from oaep-int.txt
  38. # TODO: PyCryptodome treats the message as starting *after* the leading "00"
  39. # TODO: That behaviour should probably be changed in the future.
  40. plaintext = """
  41. eb 7a 19 ac e9 e3 00 63 50 e3 29 50 4b 45 e2
  42. ca 82 31 0b 26 dc d8 7d 5c 68 f1 ee a8 f5 52 67
  43. c3 1b 2e 8b b4 25 1f 84 d7 e0 b2 c0 46 26 f5 af
  44. f9 3e dc fb 25 c9 c2 b3 ff 8a e1 0e 83 9a 2d db
  45. 4c dc fe 4f f4 77 28 b4 a1 b7 c1 36 2b aa d2 9a
  46. b4 8d 28 69 d5 02 41 21 43 58 11 59 1b e3 92 f9
  47. 82 fb 3e 87 d0 95 ae b4 04 48 db 97 2f 3a c1 4f
  48. 7b c2 75 19 52 81 ce 32 d2 f1 b7 6d 4d 35 3e 2d
  49. """
  50. ciphertext = """
  51. 12 53 e0 4d c0 a5 39 7b b4 4a 7a b8 7e 9b f2 a0
  52. 39 a3 3d 1e 99 6f c8 2a 94 cc d3 00 74 c9 5d f7
  53. 63 72 20 17 06 9e 52 68 da 5d 1c 0b 4f 87 2c f6
  54. 53 c1 1d f8 23 14 a6 79 68 df ea e2 8d ef 04 bb
  55. 6d 84 b1 c3 1d 65 4a 19 70 e5 78 3b d6 eb 96 a0
  56. 24 c2 ca 2f 4a 90 fe 9f 2e f5 c9 c1 40 e5 bb 48
  57. da 95 36 ad 87 00 c8 4f c9 13 0a de a7 4e 55 8d
  58. 51 a7 4d df 85 d8 b5 0d e9 68 38 d6 06 3e 09 55
  59. """
  60. modulus = """
  61. bb f8 2f 09 06 82 ce 9c 23 38 ac 2b 9d a8 71 f7
  62. 36 8d 07 ee d4 10 43 a4 40 d6 b6 f0 74 54 f5 1f
  63. b8 df ba af 03 5c 02 ab 61 ea 48 ce eb 6f cd 48
  64. 76 ed 52 0d 60 e1 ec 46 19 71 9d 8a 5b 8b 80 7f
  65. af b8 e0 a3 df c7 37 72 3e e6 b4 b7 d9 3a 25 84
  66. ee 6a 64 9d 06 09 53 74 88 34 b2 45 45 98 39 4e
  67. e0 aa b1 2d 7b 61 a5 1f 52 7a 9a 41 f6 c1 68 7f
  68. e2 53 72 98 ca 2a 8f 59 46 f8 e5 fd 09 1d bd cb
  69. """
  70. e = 0x11 # public exponent
  71. prime_factor = """
  72. c9 7f b1 f0 27 f4 53 f6 34 12 33 ea aa d1 d9 35
  73. 3f 6c 42 d0 88 66 b1 d0 5a 0f 20 35 02 8b 9d 86
  74. 98 40 b4 16 66 b4 2e 92 ea 0d a3 b4 32 04 b5 cf
  75. ce 33 52 52 4d 04 16 a5 a4 41 e7 00 af 46 15 03
  76. """
  77. def setUp(self):
  78. global RSA, Random, bytes_to_long
  79. from Cryptodome.PublicKey import RSA
  80. from Cryptodome import Random
  81. from Cryptodome.Util.number import bytes_to_long, inverse
  82. self.n = bytes_to_long(a2b_hex(self.modulus))
  83. self.p = bytes_to_long(a2b_hex(self.prime_factor))
  84. # Compute q, d, and u from n, e, and p
  85. self.q = self.n // self.p
  86. self.d = inverse(self.e, (self.p-1)*(self.q-1))
  87. self.u = inverse(self.p, self.q) # u = e**-1 (mod q)
  88. self.rsa = RSA
  89. def test_generate_1arg(self):
  90. """RSA (default implementation) generated key (1 argument)"""
  91. rsaObj = self.rsa.generate(1024)
  92. self._check_private_key(rsaObj)
  93. self._exercise_primitive(rsaObj)
  94. pub = rsaObj.public_key()
  95. self._check_public_key(pub)
  96. self._exercise_public_primitive(rsaObj)
  97. def test_generate_2arg(self):
  98. """RSA (default implementation) generated key (2 arguments)"""
  99. rsaObj = self.rsa.generate(1024, Random.new().read)
  100. self._check_private_key(rsaObj)
  101. self._exercise_primitive(rsaObj)
  102. pub = rsaObj.public_key()
  103. self._check_public_key(pub)
  104. self._exercise_public_primitive(rsaObj)
  105. def test_generate_3args(self):
  106. rsaObj = self.rsa.generate(1024, Random.new().read,e=65537)
  107. self._check_private_key(rsaObj)
  108. self._exercise_primitive(rsaObj)
  109. pub = rsaObj.public_key()
  110. self._check_public_key(pub)
  111. self._exercise_public_primitive(rsaObj)
  112. self.assertEqual(65537,rsaObj.e)
  113. def test_construct_2tuple(self):
  114. """RSA (default implementation) constructed key (2-tuple)"""
  115. pub = self.rsa.construct((self.n, self.e))
  116. self._check_public_key(pub)
  117. self._check_encryption(pub)
  118. def test_construct_3tuple(self):
  119. """RSA (default implementation) constructed key (3-tuple)"""
  120. rsaObj = self.rsa.construct((self.n, self.e, self.d))
  121. self._check_encryption(rsaObj)
  122. self._check_decryption(rsaObj)
  123. def test_construct_4tuple(self):
  124. """RSA (default implementation) constructed key (4-tuple)"""
  125. rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p))
  126. self._check_encryption(rsaObj)
  127. self._check_decryption(rsaObj)
  128. def test_construct_5tuple(self):
  129. """RSA (default implementation) constructed key (5-tuple)"""
  130. rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q))
  131. self._check_private_key(rsaObj)
  132. self._check_encryption(rsaObj)
  133. self._check_decryption(rsaObj)
  134. def test_construct_6tuple(self):
  135. """RSA (default implementation) constructed key (6-tuple)"""
  136. rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u))
  137. self._check_private_key(rsaObj)
  138. self._check_encryption(rsaObj)
  139. self._check_decryption(rsaObj)
  140. def test_construct_bad_key2(self):
  141. tup = (self.n, 1)
  142. self.assertRaises(ValueError, self.rsa.construct, tup)
  143. # An even modulus is wrong
  144. tup = (self.n+1, self.e)
  145. self.assertRaises(ValueError, self.rsa.construct, tup)
  146. def test_construct_bad_key3(self):
  147. tup = (self.n, self.e, self.d+1)
  148. self.assertRaises(ValueError, self.rsa.construct, tup)
  149. def test_construct_bad_key5(self):
  150. tup = (self.n, self.e, self.d, self.p, self.p)
  151. self.assertRaises(ValueError, self.rsa.construct, tup)
  152. tup = (self.p*self.p, self.e, self.p, self.p)
  153. self.assertRaises(ValueError, self.rsa.construct, tup)
  154. tup = (self.p*self.p, 3, self.p, self.q)
  155. self.assertRaises(ValueError, self.rsa.construct, tup)
  156. def test_construct_bad_key6(self):
  157. tup = (self.n, self.e, self.d, self.p, self.q, 10)
  158. self.assertRaises(ValueError, self.rsa.construct, tup)
  159. from Cryptodome.Util.number import inverse
  160. tup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p))
  161. self.assertRaises(ValueError, self.rsa.construct, tup)
  162. def test_factoring(self):
  163. rsaObj = self.rsa.construct([self.n, self.e, self.d])
  164. self.failUnless(rsaObj.p==self.p or rsaObj.p==self.q)
  165. self.failUnless(rsaObj.q==self.p or rsaObj.q==self.q)
  166. self.failUnless(rsaObj.q*rsaObj.p == self.n)
  167. self.assertRaises(ValueError, self.rsa.construct, [self.n, self.e, self.n-1])
  168. def test_repr(self):
  169. rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q))
  170. repr(rsaObj)
  171. def test_serialization(self):
  172. """RSA keys are unpickable"""
  173. rsa_key = self.rsa.generate(1024)
  174. self.assertRaises(PicklingError, pickle.dumps, rsa_key)
  175. def test_raw_rsa_boundary(self):
  176. # The argument of every RSA raw operation (encrypt/decrypt) must be
  177. # non-negative and no larger than the modulus
  178. rsa_obj = self.rsa.generate(1024)
  179. self.assertRaises(ValueError, rsa_obj._decrypt, rsa_obj.n)
  180. self.assertRaises(ValueError, rsa_obj._encrypt, rsa_obj.n)
  181. self.assertRaises(ValueError, rsa_obj._decrypt, -1)
  182. self.assertRaises(ValueError, rsa_obj._encrypt, -1)
  183. def test_size(self):
  184. pub = self.rsa.construct((self.n, self.e))
  185. self.assertEquals(pub.size_in_bits(), 1024)
  186. self.assertEquals(pub.size_in_bytes(), 128)
  187. def _check_private_key(self, rsaObj):
  188. from Cryptodome.Math.Numbers import Integer
  189. # Check capabilities
  190. self.assertEqual(1, rsaObj.has_private())
  191. # Sanity check key data
  192. self.assertEqual(rsaObj.n, rsaObj.p * rsaObj.q) # n = pq
  193. lcm = int(Integer(rsaObj.p-1).lcm(rsaObj.q-1))
  194. self.assertEqual(1, rsaObj.d * rsaObj.e % lcm) # ed = 1 (mod LCM(p-1, q-1))
  195. self.assertEqual(1, rsaObj.p * rsaObj.u % rsaObj.q) # pu = 1 (mod q)
  196. self.assertEqual(1, rsaObj.p > 1) # p > 1
  197. self.assertEqual(1, rsaObj.q > 1) # q > 1
  198. self.assertEqual(1, rsaObj.e > 1) # e > 1
  199. self.assertEqual(1, rsaObj.d > 1) # d > 1
  200. def _check_public_key(self, rsaObj):
  201. ciphertext = a2b_hex(self.ciphertext)
  202. # Check capabilities
  203. self.assertEqual(0, rsaObj.has_private())
  204. # Check rsaObj.[ne] -> rsaObj.[ne] mapping
  205. self.assertEqual(rsaObj.n, rsaObj.n)
  206. self.assertEqual(rsaObj.e, rsaObj.e)
  207. # Check that private parameters are all missing
  208. self.assertEqual(0, hasattr(rsaObj, 'd'))
  209. self.assertEqual(0, hasattr(rsaObj, 'p'))
  210. self.assertEqual(0, hasattr(rsaObj, 'q'))
  211. self.assertEqual(0, hasattr(rsaObj, 'u'))
  212. # Sanity check key data
  213. self.assertEqual(1, rsaObj.e > 1) # e > 1
  214. # Public keys should not be able to sign or decrypt
  215. self.assertRaises(TypeError, rsaObj._decrypt,
  216. bytes_to_long(ciphertext))
  217. # Check __eq__ and __ne__
  218. self.assertEqual(rsaObj.public_key() == rsaObj.public_key(),True) # assert_
  219. self.assertEqual(rsaObj.public_key() != rsaObj.public_key(),False) # failIf
  220. self.assertEqual(rsaObj.publickey(), rsaObj.public_key())
  221. def _exercise_primitive(self, rsaObj):
  222. # Since we're using a randomly-generated key, we can't check the test
  223. # vector, but we can make sure encryption and decryption are inverse
  224. # operations.
  225. ciphertext = bytes_to_long(a2b_hex(self.ciphertext))
  226. # Test decryption
  227. plaintext = rsaObj._decrypt(ciphertext)
  228. # Test encryption (2 arguments)
  229. new_ciphertext2 = rsaObj._encrypt(plaintext)
  230. self.assertEqual(ciphertext, new_ciphertext2)
  231. def _exercise_public_primitive(self, rsaObj):
  232. plaintext = a2b_hex(self.plaintext)
  233. # Test encryption (2 arguments)
  234. new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
  235. def _check_encryption(self, rsaObj):
  236. plaintext = a2b_hex(self.plaintext)
  237. ciphertext = a2b_hex(self.ciphertext)
  238. # Test encryption
  239. new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
  240. self.assertEqual(bytes_to_long(ciphertext), new_ciphertext2)
  241. def _check_decryption(self, rsaObj):
  242. plaintext = bytes_to_long(a2b_hex(self.plaintext))
  243. ciphertext = bytes_to_long(a2b_hex(self.ciphertext))
  244. # Test plain decryption
  245. new_plaintext = rsaObj._decrypt(ciphertext)
  246. self.assertEqual(plaintext, new_plaintext)
  247. def get_tests(config={}):
  248. tests = []
  249. tests += list_test_cases(RSATest)
  250. return tests
  251. if __name__ == '__main__':
  252. suite = lambda: unittest.TestSuite(get_tests())
  253. unittest.main(defaultTest='suite')
  254. # vim:set ts=4 sw=4 sts=4 expandtab: