Debian Codegraph @

lib/Crypto/SelfTest/Cipher/common.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # SelfTest/Hash/common.py: Common code for Crypto.SelfTest.Hash
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-testing for PyCrypto hash modules"""
26
27 import unittest
28 from binascii import a2b_hex, b2a_hex, hexlify
29
30 from Crypto.Util.py3compat import b
31 from Crypto.Util.strxor import strxor_c
32
33 class _NoDefault: pass # sentinel object
34 def _extract(d, k, default=_NoDefault):
35 """Get an item from a dictionary, and remove it from the dictionary."""
36 try:
37 retval = d[k]
38 except KeyError:
39 if default is _NoDefault:
40 raise
41 return default
42 del d[k]
43 return retval
44
45 # Generic cipher test case
46 class CipherSelfTest(unittest.TestCase):
47
48 def __init__(self, module, params):
49 unittest.TestCase.__init__(self)
50 self.module = module
51
52 # Extract the parameters
53 params = params.copy()
54 self.description = _extract(params, 'description')
55 self.key = b(_extract(params, 'key'))
56 self.plaintext = b(_extract(params, 'plaintext'))
57 self.ciphertext = b(_extract(params, 'ciphertext'))
58 self.module_name = _extract(params, 'module_name', None)
59 self.assoc_data = _extract(params, 'assoc_data', None)
60 self.mac = _extract(params, 'mac', None)
61 if self.assoc_data:
62 self.mac = b(self.mac)
63
64 mode = _extract(params, 'mode', None)
65 self.mode_name = str(mode)
66
67 if mode is not None:
68 # Block cipher
69 self.mode = getattr(self.module, "MODE_" + mode)
70
71 self.iv = _extract(params, 'iv', None)
72 if self.iv is None:
73 self.iv = _extract(params, 'nonce', None)
74 if self.iv is not None:
75 self.iv = b(self.iv)
76
77 else:
78 # Stream cipher
79 self.mode = None
80 self.iv = _extract(params, 'iv', None)
81 if self.iv is not None:
82 self.iv = b(self.iv)
83
84 self.extra_params = params
85
86 def shortDescription(self):
87 return self.description
88
89 def _new(self):
90 params = self.extra_params.copy()
91 key = a2b_hex(self.key)
92
93 old_style = []
94 if self.mode is not None:
95 old_style = [ self.mode ]
96 if self.iv is not None:
97 old_style += [ a2b_hex(self.iv) ]
98
99 return self.module.new(key, *old_style, **params)
100
101 def isMode(self, name):
102 if not hasattr(self.module, "MODE_"+name):
103 return False
104 return self.mode == getattr(self.module, "MODE_"+name)
105
106 def runTest(self):
107 plaintext = a2b_hex(self.plaintext)
108 ciphertext = a2b_hex(self.ciphertext)
109 assoc_data = []
110 if self.assoc_data:
111 assoc_data = [ a2b_hex(b(x)) for x in self.assoc_data]
112
113 ct = None
114 pt = None
115
116 #
117 # Repeat the same encryption or decryption twice and verify
118 # that the result is always the same
119 #
120 for i in range(2):
121 cipher = self._new()
122 decipher = self._new()
123
124 # Only AEAD modes
125 for comp in assoc_data:
126 cipher.update(comp)
127 decipher.update(comp)
128
129 ctX = b2a_hex(cipher.encrypt(plaintext))
130 ptX = b2a_hex(decipher.decrypt(ciphertext))
131
132 if ct:
133 self.assertEqual(ct, ctX)
134 self.assertEqual(pt, ptX)
135 ct, pt = ctX, ptX
136
137 self.assertEqual(self.ciphertext, ct) # encrypt
138 self.assertEqual(self.plaintext, pt) # decrypt
139
140 if self.mac:
141 mac = b2a_hex(cipher.digest())
142 self.assertEqual(self.mac, mac)
143 decipher.verify(a2b_hex(self.mac))
144
145 class CipherStreamingSelfTest(CipherSelfTest):
146
147 def shortDescription(self):
148 desc = self.module_name
149 if self.mode is not None:
150 desc += " in %s mode" % (self.mode_name,)
151 return "%s should behave like a stream cipher" % (desc,)
152
153 def runTest(self):
154 plaintext = a2b_hex(self.plaintext)
155 ciphertext = a2b_hex(self.ciphertext)
156
157 # The cipher should work like a stream cipher
158
159 # Test counter mode encryption, 3 bytes at a time
160 ct3 = []
161 cipher = self._new()
162 for i in range(0, len(plaintext), 3):
163 ct3.append(cipher.encrypt(plaintext[i:i+3]))
164 ct3 = b2a_hex(b("").join(ct3))
165 self.assertEqual(self.ciphertext, ct3) # encryption (3 bytes at a time)
166
167 # Test counter mode decryption, 3 bytes at a time
168 pt3 = []
169 cipher = self._new()
170 for i in range(0, len(ciphertext), 3):
171 pt3.append(cipher.encrypt(ciphertext[i:i+3]))
172 # PY3K: This is meant to be text, do not change to bytes (data)
173 pt3 = b2a_hex(b("").join(pt3))
174 self.assertEqual(self.plaintext, pt3) # decryption (3 bytes at a time)
175
176
177 class RoundtripTest(unittest.TestCase):
178 def __init__(self, module, params):
179 from Crypto import Random
180 unittest.TestCase.__init__(self)
181 self.module = module
182 self.iv = Random.get_random_bytes(module.block_size)
183 self.key = b(params['key'])
184 self.plaintext = 100 * b(params['plaintext'])
185 self.module_name = params.get('module_name', None)
186
187 def shortDescription(self):
188 return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
189
190 def runTest(self):
191
192 ## ECB mode
193 mode = self.module.MODE_ECB
194 encryption_cipher = self.module.new(a2b_hex(self.key), mode)
195 ciphertext = encryption_cipher.encrypt(self.plaintext)
196 decryption_cipher = self.module.new(a2b_hex(self.key), mode)
197 decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
198 self.assertEqual(self.plaintext, decrypted_plaintext)
199
200
201 class IVLengthTest(unittest.TestCase):
202 def __init__(self, module, params):
203 unittest.TestCase.__init__(self)
204 self.module = module
205 self.key = b(params['key'])
206
207 def shortDescription(self):
208 return "Check that all modes except MODE_ECB and MODE_CTR require an IV of the proper length"
209
210 def runTest(self):
211 self.assertRaises(TypeError, self.module.new, a2b_hex(self.key),
212 self.module.MODE_ECB, b(""))
213
214 def _dummy_counter(self):
215 return "\0" * self.module.block_size
216
217
218 class NoDefaultECBTest(unittest.TestCase):
219 def __init__(self, module, params):
220 unittest.TestCase.__init__(self)
221 self.module = module
222 self.key = b(params['key'])
223
224 def runTest(self):
225 self.assertRaises(TypeError, self.module.new, a2b_hex(self.key))
226
227
228 class BlockSizeTest(unittest.TestCase):
229 def __init__(self, module, params):
230 unittest.TestCase.__init__(self)
231 self.module = module
232 self.key = a2b_hex(b(params['key']))
233
234 def runTest(self):
235 cipher = self.module.new(self.key, self.module.MODE_ECB)
236 self.assertEqual(cipher.block_size, self.module.block_size)
237
238
239 class ByteArrayTest(unittest.TestCase):
240 """Verify we can use bytearray's for encrypting and decrypting"""
241
242 def __init__(self, module, params):
243 unittest.TestCase.__init__(self)
244 self.module = module
245
246 # Extract the parameters
247 params = params.copy()
248 self.description = _extract(params, 'description')
249 self.key = b(_extract(params, 'key'))
250 self.plaintext = b(_extract(params, 'plaintext'))
251 self.ciphertext = b(_extract(params, 'ciphertext'))
252 self.module_name = _extract(params, 'module_name', None)
253 self.assoc_data = _extract(params, 'assoc_data', None)
254 self.mac = _extract(params, 'mac', None)
255 if self.assoc_data:
256 self.mac = b(self.mac)
257
258 mode = _extract(params, 'mode', None)
259 self.mode_name = str(mode)
260
261 if mode is not None:
262 # Block cipher
263 self.mode = getattr(self.module, "MODE_" + mode)
264
265 self.iv = _extract(params, 'iv', None)
266 if self.iv is None:
267 self.iv = _extract(params, 'nonce', None)
268 if self.iv is not None:
269 self.iv = b(self.iv)
270 else:
271 # Stream cipher
272 self.mode = None
273 self.iv = _extract(params, 'iv', None)
274 if self.iv is not None:
275 self.iv = b(self.iv)
276
277 self.extra_params = params
278
279 def _new(self):
280 params = self.extra_params.copy()
281 key = a2b_hex(self.key)
282
283 old_style = []
284 if self.mode is not None:
285 old_style = [ self.mode ]
286 if self.iv is not None:
287 old_style += [ a2b_hex(self.iv) ]
288
289 return self.module.new(key, *old_style, **params)
290
291 def runTest(self):
292
293 plaintext = a2b_hex(self.plaintext)
294 ciphertext = a2b_hex(self.ciphertext)
295 assoc_data = []
296 if self.assoc_data:
297 assoc_data = [ bytearray(a2b_hex(b(x))) for x in self.assoc_data]
298
299 cipher = self._new()
300 decipher = self._new()
301
302 # Only AEAD modes
303 for comp in assoc_data:
304 cipher.update(comp)
305 decipher.update(comp)
306
307 ct = b2a_hex(cipher.encrypt(bytearray(plaintext)))
308 pt = b2a_hex(decipher.decrypt(bytearray(ciphertext)))
309
310 self.assertEqual(self.ciphertext, ct) # encrypt
311 self.assertEqual(self.plaintext, pt) # decrypt
312
313 if self.mac:
314 mac = b2a_hex(cipher.digest())
315 self.assertEqual(self.mac, mac)
316 decipher.verify(bytearray(a2b_hex(self.mac)))
317
318
319 class MemoryviewTest(unittest.TestCase):
320 """Verify we can use memoryviews for encrypting and decrypting"""
321
322 def __init__(self, module, params):
323 unittest.TestCase.__init__(self)
324 self.module = module
325
326 # Extract the parameters
327 params = params.copy()
328 self.description = _extract(params, 'description')
329 self.key = b(_extract(params, 'key'))
330 self.plaintext = b(_extract(params, 'plaintext'))
331 self.ciphertext = b(_extract(params, 'ciphertext'))
332 self.module_name = _extract(params, 'module_name', None)
333 self.assoc_data = _extract(params, 'assoc_data', None)
334 self.mac = _extract(params, 'mac', None)
335 if self.assoc_data:
336 self.mac = b(self.mac)
337
338 mode = _extract(params, 'mode', None)
339 self.mode_name = str(mode)
340
341 if mode is not None:
342 # Block cipher
343 self.mode = getattr(self.module, "MODE_" + mode)
344
345 self.iv = _extract(params, 'iv', None)
346 if self.iv is None:
347 self.iv = _extract(params, 'nonce', None)
348 if self.iv is not None:
349 self.iv = b(self.iv)
350 else:
351 # Stream cipher
352 self.mode = None
353 self.iv = _extract(params, 'iv', None)
354 if self.iv is not None:
355 self.iv = b(self.iv)
356
357 self.extra_params = params
358
359 def _new(self):
360 params = self.extra_params.copy()
361 key = a2b_hex(self.key)
362
363 old_style = []
364 if self.mode is not None:
365 old_style = [ self.mode ]
366 if self.iv is not None:
367 old_style += [ a2b_hex(self.iv) ]
368
369 return self.module.new(key, *old_style, **params)
370
371 def runTest(self):
372
373 plaintext = a2b_hex(self.plaintext)
374 ciphertext = a2b_hex(self.ciphertext)
375 assoc_data = []
376 if self.assoc_data:
377 assoc_data = [ memoryview(a2b_hex(b(x))) for x in self.assoc_data]
378
379 cipher = self._new()
380 decipher = self._new()
381
382 # Only AEAD modes
383 for comp in assoc_data:
384 cipher.update(comp)
385 decipher.update(comp)
386
387 ct = b2a_hex(cipher.encrypt(memoryview(plaintext)))
388 pt = b2a_hex(decipher.decrypt(memoryview(ciphertext)))
389
390 self.assertEqual(self.ciphertext, ct) # encrypt
391 self.assertEqual(self.plaintext, pt) # decrypt
392
393 if self.mac:
394 mac = b2a_hex(cipher.digest())
395 self.assertEqual(self.mac, mac)
396 decipher.verify(memoryview(a2b_hex(self.mac)))
397
398
399 def make_block_tests(module, module_name, test_data, additional_params=dict()):
400 tests = []
401 extra_tests_added = False
402 for i in range(len(test_data)):
403 row = test_data[i]
404
405 # Build the "params" dictionary with
406 # - plaintext
407 # - ciphertext
408 # - key
409 # - mode (default is ECB)
410 # - (optionally) description
411 # - (optionally) any other parameter that this cipher mode requires
412 params = {}
413 if len(row) == 3:
414 (params['plaintext'], params['ciphertext'], params['key']) = row
415 elif len(row) == 4:
416 (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
417 elif len(row) == 5:
418 (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
419 params.update(extra_params)
420 else:
421 raise AssertionError("Unsupported tuple size %d" % (len(row),))
422
423 if not "mode" in params:
424 params["mode"] = "ECB"
425
426 # Build the display-name for the test
427 p2 = params.copy()
428 p_key = _extract(p2, 'key')
429 p_plaintext = _extract(p2, 'plaintext')
430 p_ciphertext = _extract(p2, 'ciphertext')
431 p_mode = _extract(p2, 'mode')
432 p_description = _extract(p2, 'description', None)
433
434 if p_description is not None:
435 description = p_description
436 elif p_mode == 'ECB' and not p2:
437 description = "p=%s, k=%s" % (p_plaintext, p_key)
438 else:
439 description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
440 name = "%s #%d: %s" % (module_name, i+1, description)
441 params['description'] = name
442 params['module_name'] = module_name
443 params.update(additional_params)
444
445 # Add extra test(s) to the test suite before the current test
446 if not extra_tests_added:
447 tests += [
448 RoundtripTest(module, params),
449 IVLengthTest(module, params),
450 NoDefaultECBTest(module, params),
451 ByteArrayTest(module, params),
452 BlockSizeTest(module, params),
453 ]
454 extra_tests_added = True
455
456 # Add the current test to the test suite
457 tests.append(CipherSelfTest(module, params))
458
459 return tests
460
461 def make_stream_tests(module, module_name, test_data):
462 tests = []
463 extra_tests_added = False
464 for i in range(len(test_data)):
465 row = test_data[i]
466
467 # Build the "params" dictionary
468 params = {}
469 if len(row) == 3:
470 (params['plaintext'], params['ciphertext'], params['key']) = row
471 elif len(row) == 4:
472 (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
473 elif len(row) == 5:
474 (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
475 params.update(extra_params)
476 else:
477 raise AssertionError("Unsupported tuple size %d" % (len(row),))
478
479 # Build the display-name for the test
480 p2 = params.copy()
481 p_key = _extract(p2, 'key')
482 p_plaintext = _extract(p2, 'plaintext')
483 p_ciphertext = _extract(p2, 'ciphertext')
484 p_description = _extract(p2, 'description', None)
485
486 if p_description is not None:
487 description = p_description
488 elif not p2:
489 description = "p=%s, k=%s" % (p_plaintext, p_key)
490 else:
491 description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
492 name = "%s #%d: %s" % (module_name, i+1, description)
493 params['description'] = name
494 params['module_name'] = module_name
495
496 # Add extra test(s) to the test suite before the current test
497 if not extra_tests_added:
498 tests += [
499 ByteArrayTest(module, params),
500 ]
501
502 tests.append(MemoryviewTest(module, params))
503 extra_tests_added = True
504
505 # Add the test to the test suite
506 tests.append(CipherSelfTest(module, params))
507 tests.append(CipherStreamingSelfTest(module, params))
508 return tests
509
510 # vim:set ts=4 sw=4 sts=4 expandtab: