Debian Codegraph @

lib/Crypto/SelfTest/PublicKey/test_RSA.py

raw symbols SCIP
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 <[email protected]>
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
25 """Self-test suite for Crypto.PublicKey.RSA"""
26
27 __revision__ = "$Id$"
28
29 import os
30 import pickle
31 from pickle import PicklingError
32 from Crypto.Util.py3compat import *
33
34 import unittest
35 from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
36
37 class RSATest(unittest.TestCase):
38 # Test vectors from "RSA-OAEP and RSA-PSS test vectors (.zip file)"
39 # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip
40 # See RSADSI's PKCS#1 page at
41 # http://www.rsa.com/rsalabs/node.asp?id=2125
42
43 # from oaep-int.txt
44
45 # TODO: PyCrypto treats the message as starting *after* the leading "00"
46 # TODO: That behaviour should probably be changed in the future.
47 plaintext = """
48 eb 7a 19 ac e9 e3 00 63 50 e3 29 50 4b 45 e2
49 ca 82 31 0b 26 dc d8 7d 5c 68 f1 ee a8 f5 52 67
50 c3 1b 2e 8b b4 25 1f 84 d7 e0 b2 c0 46 26 f5 af
51 f9 3e dc fb 25 c9 c2 b3 ff 8a e1 0e 83 9a 2d db
52 4c dc fe 4f f4 77 28 b4 a1 b7 c1 36 2b aa d2 9a
53 b4 8d 28 69 d5 02 41 21 43 58 11 59 1b e3 92 f9
54 82 fb 3e 87 d0 95 ae b4 04 48 db 97 2f 3a c1 4f
55 7b c2 75 19 52 81 ce 32 d2 f1 b7 6d 4d 35 3e 2d
56 """
57
58 ciphertext = """
59 12 53 e0 4d c0 a5 39 7b b4 4a 7a b8 7e 9b f2 a0
60 39 a3 3d 1e 99 6f c8 2a 94 cc d3 00 74 c9 5d f7
61 63 72 20 17 06 9e 52 68 da 5d 1c 0b 4f 87 2c f6
62 53 c1 1d f8 23 14 a6 79 68 df ea e2 8d ef 04 bb
63 6d 84 b1 c3 1d 65 4a 19 70 e5 78 3b d6 eb 96 a0
64 24 c2 ca 2f 4a 90 fe 9f 2e f5 c9 c1 40 e5 bb 48
65 da 95 36 ad 87 00 c8 4f c9 13 0a de a7 4e 55 8d
66 51 a7 4d df 85 d8 b5 0d e9 68 38 d6 06 3e 09 55
67 """
68
69 modulus = """
70 bb f8 2f 09 06 82 ce 9c 23 38 ac 2b 9d a8 71 f7
71 36 8d 07 ee d4 10 43 a4 40 d6 b6 f0 74 54 f5 1f
72 b8 df ba af 03 5c 02 ab 61 ea 48 ce eb 6f cd 48
73 76 ed 52 0d 60 e1 ec 46 19 71 9d 8a 5b 8b 80 7f
74 af b8 e0 a3 df c7 37 72 3e e6 b4 b7 d9 3a 25 84
75 ee 6a 64 9d 06 09 53 74 88 34 b2 45 45 98 39 4e
76 e0 aa b1 2d 7b 61 a5 1f 52 7a 9a 41 f6 c1 68 7f
77 e2 53 72 98 ca 2a 8f 59 46 f8 e5 fd 09 1d bd cb
78 """
79
80 e = 0x11 # public exponent
81
82 prime_factor = """
83 c9 7f b1 f0 27 f4 53 f6 34 12 33 ea aa d1 d9 35
84 3f 6c 42 d0 88 66 b1 d0 5a 0f 20 35 02 8b 9d 86
85 98 40 b4 16 66 b4 2e 92 ea 0d a3 b4 32 04 b5 cf
86 ce 33 52 52 4d 04 16 a5 a4 41 e7 00 af 46 15 03
87 """
88
89 def setUp(self):
90 global RSA, Random, bytes_to_long
91 from Crypto.PublicKey import RSA
92 from Crypto import Random
93 from Crypto.Util.number import bytes_to_long, inverse
94 self.n = bytes_to_long(a2b_hex(self.modulus))
95 self.p = bytes_to_long(a2b_hex(self.prime_factor))
96
97 # Compute q, d, and u from n, e, and p
98 self.q = self.n // self.p
99 self.d = inverse(self.e, (self.p-1)*(self.q-1))
100 self.u = inverse(self.p, self.q) # u = e**-1 (mod q)
101
102 self.rsa = RSA
103
104 def test_generate_1arg(self):
105 """RSA (default implementation) generated key (1 argument)"""
106 rsaObj = self.rsa.generate(1024)
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
113 def test_generate_2arg(self):
114 """RSA (default implementation) generated key (2 arguments)"""
115 rsaObj = self.rsa.generate(1024, Random.new().read)
116 self._check_private_key(rsaObj)
117 self._exercise_primitive(rsaObj)
118 pub = rsaObj.public_key()
119 self._check_public_key(pub)
120 self._exercise_public_primitive(rsaObj)
121
122 def test_generate_3args(self):
123 rsaObj = self.rsa.generate(1024, Random.new().read,e=65537)
124 self._check_private_key(rsaObj)
125 self._exercise_primitive(rsaObj)
126 pub = rsaObj.public_key()
127 self._check_public_key(pub)
128 self._exercise_public_primitive(rsaObj)
129 self.assertEqual(65537,rsaObj.e)
130
131 def test_construct_2tuple(self):
132 """RSA (default implementation) constructed key (2-tuple)"""
133 pub = self.rsa.construct((self.n, self.e))
134 self._check_public_key(pub)
135 self._check_encryption(pub)
136
137 def test_construct_3tuple(self):
138 """RSA (default implementation) constructed key (3-tuple)"""
139 rsaObj = self.rsa.construct((self.n, self.e, self.d))
140 self._check_encryption(rsaObj)
141 self._check_decryption(rsaObj)
142
143 def test_construct_4tuple(self):
144 """RSA (default implementation) constructed key (4-tuple)"""
145 rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p))
146 self._check_encryption(rsaObj)
147 self._check_decryption(rsaObj)
148
149 def test_construct_5tuple(self):
150 """RSA (default implementation) constructed key (5-tuple)"""
151 rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q))
152 self._check_private_key(rsaObj)
153 self._check_encryption(rsaObj)
154 self._check_decryption(rsaObj)
155
156 def test_construct_6tuple(self):
157 """RSA (default implementation) constructed key (6-tuple)"""
158 rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q, self.u))
159 self._check_private_key(rsaObj)
160 self._check_encryption(rsaObj)
161 self._check_decryption(rsaObj)
162
163 def test_construct_bad_key2(self):
164 tup = (self.n, 1)
165 self.assertRaises(ValueError, self.rsa.construct, tup)
166
167 # An even modulus is wrong
168 tup = (self.n+1, self.e)
169 self.assertRaises(ValueError, self.rsa.construct, tup)
170
171 def test_construct_bad_key3(self):
172 tup = (self.n, self.e, self.d+1)
173 self.assertRaises(ValueError, self.rsa.construct, tup)
174
175 def test_construct_bad_key5(self):
176 tup = (self.n, self.e, self.d, self.p, self.p)
177 self.assertRaises(ValueError, self.rsa.construct, tup)
178
179 tup = (self.p*self.p, self.e, self.p, self.p)
180 self.assertRaises(ValueError, self.rsa.construct, tup)
181
182 tup = (self.p*self.p, 3, self.p, self.q)
183 self.assertRaises(ValueError, self.rsa.construct, tup)
184
185 def test_construct_bad_key6(self):
186 tup = (self.n, self.e, self.d, self.p, self.q, 10)
187 self.assertRaises(ValueError, self.rsa.construct, tup)
188
189 from Crypto.Util.number import inverse
190 tup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p))
191 self.assertRaises(ValueError, self.rsa.construct, tup)
192
193 def test_factoring(self):
194 rsaObj = self.rsa.construct([self.n, self.e, self.d])
195 self.assertTrue(rsaObj.p==self.p or rsaObj.p==self.q)
196 self.assertTrue(rsaObj.q==self.p or rsaObj.q==self.q)
197 self.assertTrue(rsaObj.q*rsaObj.p == self.n)
198
199 self.assertRaises(ValueError, self.rsa.construct, [self.n, self.e, self.n-1])
200
201 def test_repr(self):
202 rsaObj = self.rsa.construct((self.n, self.e, self.d, self.p, self.q))
203 repr(rsaObj)
204
205 def test_serialization(self):
206 """RSA keys are unpickable"""
207
208 rsa_key = self.rsa.generate(1024)
209 self.assertRaises(PicklingError, pickle.dumps, rsa_key)
210
211 def test_raw_rsa_boundary(self):
212 # The argument of every RSA raw operation (encrypt/decrypt) must be
213 # non-negative and no larger than the modulus
214 rsa_obj = self.rsa.generate(1024)
215
216 self.assertRaises(ValueError, rsa_obj._decrypt, rsa_obj.n)
217 self.assertRaises(ValueError, rsa_obj._decrypt_to_bytes, rsa_obj.n)
218 self.assertRaises(ValueError, rsa_obj._encrypt, rsa_obj.n)
219
220 self.assertRaises(ValueError, rsa_obj._decrypt, -1)
221 self.assertRaises(ValueError, rsa_obj._decrypt_to_bytes, -1)
222 self.assertRaises(ValueError, rsa_obj._encrypt, -1)
223
224 def test_size(self):
225 pub = self.rsa.construct((self.n, self.e))
226 self.assertEqual(pub.size_in_bits(), 1024)
227 self.assertEqual(pub.size_in_bytes(), 128)
228
229 def _check_private_key(self, rsaObj):
230 from Crypto.Math.Numbers import Integer
231
232 # Check capabilities
233 self.assertEqual(1, rsaObj.has_private())
234
235 # Sanity check key data
236 self.assertEqual(rsaObj.n, rsaObj.p * rsaObj.q) # n = pq
237 lcm = int(Integer(rsaObj.p-1).lcm(rsaObj.q-1))
238 self.assertEqual(1, rsaObj.d * rsaObj.e % lcm) # ed = 1 (mod LCM(p-1, q-1))
239 self.assertEqual(1, rsaObj.p * rsaObj.u % rsaObj.q) # pu = 1 (mod q)
240 self.assertEqual(1, rsaObj.p > 1) # p > 1
241 self.assertEqual(1, rsaObj.q > 1) # q > 1
242 self.assertEqual(1, rsaObj.e > 1) # e > 1
243 self.assertEqual(1, rsaObj.d > 1) # d > 1
244
245 self.assertEqual(rsaObj.u, rsaObj.invp)
246 self.assertEqual(1, rsaObj.q * rsaObj.invq % rsaObj.p)
247
248 def _check_public_key(self, rsaObj):
249 ciphertext = a2b_hex(self.ciphertext)
250
251 # Check capabilities
252 self.assertEqual(0, rsaObj.has_private())
253
254 # Check rsaObj.[ne] -> rsaObj.[ne] mapping
255 self.assertEqual(rsaObj.n, rsaObj.n)
256 self.assertEqual(rsaObj.e, rsaObj.e)
257
258 # Check that private parameters are all missing
259 self.assertEqual(0, hasattr(rsaObj, 'd'))
260 self.assertEqual(0, hasattr(rsaObj, 'p'))
261 self.assertEqual(0, hasattr(rsaObj, 'q'))
262 self.assertEqual(0, hasattr(rsaObj, 'u'))
263
264 # Sanity check key data
265 self.assertEqual(1, rsaObj.e > 1) # e > 1
266
267 # Public keys should not be able to sign or decrypt
268 self.assertRaises(TypeError, rsaObj._decrypt,
269 bytes_to_long(ciphertext))
270 self.assertRaises(TypeError, rsaObj._decrypt_to_bytes,
271 bytes_to_long(ciphertext))
272
273 # Check __eq__ and __ne__
274 self.assertEqual(rsaObj.public_key() == rsaObj.public_key(),True) # assert_
275 self.assertEqual(rsaObj.public_key() != rsaObj.public_key(),False) # assertFalse
276
277 self.assertEqual(rsaObj.publickey(), rsaObj.public_key())
278
279 def _exercise_primitive(self, rsaObj):
280 # Since we're using a randomly-generated key, we can't check the test
281 # vector, but we can make sure encryption and decryption are inverse
282 # operations.
283 ciphertext = bytes_to_long(a2b_hex(self.ciphertext))
284
285 # Test decryption
286 plaintext = rsaObj._decrypt(ciphertext)
287
288 # Test encryption (2 arguments)
289 new_ciphertext2 = rsaObj._encrypt(plaintext)
290 self.assertEqual(ciphertext, new_ciphertext2)
291
292 def _exercise_public_primitive(self, rsaObj):
293 plaintext = a2b_hex(self.plaintext)
294
295 # Test encryption (2 arguments)
296 new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
297
298 def _check_encryption(self, rsaObj):
299 plaintext = a2b_hex(self.plaintext)
300 ciphertext = a2b_hex(self.ciphertext)
301
302 # Test encryption
303 new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
304 self.assertEqual(bytes_to_long(ciphertext), new_ciphertext2)
305
306 def _check_decryption(self, rsaObj):
307 plaintext = bytes_to_long(a2b_hex(self.plaintext))
308 ciphertext = bytes_to_long(a2b_hex(self.ciphertext))
309
310 # Test plain decryption
311 new_plaintext = rsaObj._decrypt(ciphertext)
312 self.assertEqual(plaintext, new_plaintext)
313
314
315 def get_tests(config={}):
316 tests = []
317 tests += list_test_cases(RSATest)
318 return tests
319
320 if __name__ == '__main__':
321 suite = lambda: unittest.TestSuite(get_tests())
322 unittest.main(defaultTest='suite')
323
324 # vim:set ts=4 sw=4 sts=4 expandtab: