Debian Codegraph @

lib/Crypto/SelfTest/Signature/test_pss.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 import unittest
32
33 from Crypto.Util.py3compat import b, bchr
34 from Crypto.Util.number import bytes_to_long
35 from Crypto.Util.strxor import strxor
36 from Crypto.SelfTest.st_common import list_test_cases
37 from Crypto.SelfTest.loader import load_test_vectors, load_test_vectors_wycheproof
38
39 from Crypto.Hash import SHA1, SHA224, SHA256, SHA384, SHA512
40 from Crypto.PublicKey import RSA
41 from Crypto.Signature import pss
42 from Crypto.Signature import PKCS1_PSS
43
44 from Crypto.Signature.pss import MGF1
45
46
47 def load_hash_by_name(hash_name):
48 return __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"])
49
50
51 class PRNG(object):
52
53 def __init__(self, stream):
54 self.stream = stream
55 self.idx = 0
56
57 def __call__(self, rnd_size):
58 result = self.stream[self.idx:self.idx + rnd_size]
59 self.idx += rnd_size
60 return result
61
62
63 class PSS_Tests(unittest.TestCase):
64
65 rsa_key = b'-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAsvI34FgiTK8+txBvmooNGpNwk23YTU51dwNZi5yha3W4lA/Q\nvcZrDalkmD7ekWQwnduxVKa6pRSI13KBgeUOIqJoGXSWhntEtY3FEwvWOHW5AE7Q\njUzTzCiYT6TVaCcpa/7YLai+p6ai2g5f5Zfh4jSawa9uYeuggFygQq4IVW796MgV\nyqxYMM/arEj+/sKz3Viua9Rp9fFosertCYCX4DUTgW0mX9bwEnEOgjSI3pLOPXz1\n8vx+DRZS5wMCmwCUa0sKonLn3cAUPq+sGix7+eo7T0Z12MU8ud7IYVX/75r3cXiF\nPaYE2q8Le0kgOApIXbb+x74x0rNgyIh1yGygkwIDAQABAoIBABz4t1A0pLT6qHI2\nEIOaNz3mwhK0dZEqkz0GB1Dhtoax5ATgvKCFB98J3lYB08IBURe1snOsnMpOVUtg\naBRSM+QqnCUG6bnzKjAkuFP5liDE+oNQv1YpKp9CsUovuzdmI8Au3ewihl+ZTIN2\nUVNYMEOR1b5m+z2SSwWNOYsiJwpBrT7zkpdlDyjat7FiiPhMMIMXjhQFVxURMIcB\njUBtPzGvV/PG90cVDWi1wRGeeP1dDqti/jsnvykQ15KW1MqGrpeNKRmDdTy/Ucl1\nWIoYklKw3U456lgZ/rDTDB818+Tlnk35z4yF7d5ANPM8CKfqOPcnO1BCKVFzf4eq\n54wvUtkCgYEA1Zv2lp06l7rXMsv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\xbb\xec\xfe\xb0\xa5\xb9\x08\x11P\x8fL\xee5\x9b\xb0k{=_\xd2\x14\xfb\x01R\xb7\xfe\x14}b\x03\x8d5Y\x89~}\xfc\xf2l\xd01-\xbd\xeb\x11\xcdV\x11\xe9l\x19k/o5\xa2\x0f\x15\xe7Q$\t=\xec\x1dAB\x19\xa5P\x9a\xaf\xa3G\x86"\xd6~\xf0<p5\x00\x86\xe0\xf3\x99\xc7+\xcfc,\\\x13)v\xcd\xff\x08o\x90\xc5\xd1\xca\x869\xf45\x1e\xfd\xa2\xf1n\xa3\xa6e\xc5\x11Q\xe4@\xbd\x17\x83x\xc9\x9b\xb5\xc7\xea\x03U\x9b\xa0\xccC\x17\xc9T\x86/\x05\x1c\xc7\x95hC\xf9b1\xbb\x05\xc3\xf0\x9a>j\xfcqkbs\x13\x84b\xe4\xbdm(\xed`\xa4F\xfb\x8f.\xe1\x8c)/_\x9eS\x98\xa4v\xb8\xdc\xfe\xf7/D\x18\x19\xb3T\x97:\xe2\x96s\xe8<\xa2\xb4\xb9\xf8/'
68
69 def test_positive_1(self):
70 key = RSA.import_key(self.rsa_key)
71 h = SHA256.new(self.msg)
72 verifier = pss.new(key)
73 verifier.verify(h, self.tag)
74
75 def test_negative_1(self):
76 key = RSA.import_key(self.rsa_key)
77 h = SHA256.new(self.msg + b'A')
78 verifier = pss.new(key)
79 tag = bytearray(self.tag)
80 self.assertRaises(ValueError, verifier.verify, h, tag)
81
82 def test_negative_2(self):
83 key = RSA.import_key(self.rsa_key)
84 h = SHA256.new(self.msg)
85 verifier = pss.new(key, salt_bytes=1000)
86 tag = bytearray(self.tag)
87 self.assertRaises(ValueError, verifier.verify, h, tag)
88
89
90 class FIPS_PKCS1_Verify_Tests(unittest.TestCase):
91
92 def shortDescription(self):
93 return "FIPS PKCS1 Tests (Verify)"
94
95 def verify_positive(self, hashmod, message, public_key, salt, signature):
96 prng = PRNG(salt)
97 hashed = hashmod.new(message)
98 verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng)
99 verifier.verify(hashed, signature)
100
101 def verify_negative(self, hashmod, message, public_key, salt, signature):
102 prng = PRNG(salt)
103 hashed = hashmod.new(message)
104 verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng)
105 self.assertRaises(ValueError, verifier.verify, hashed, signature)
106
107 def test_can_sign(self):
108 test_public_key = RSA.generate(1024).public_key()
109 verifier = pss.new(test_public_key)
110 self.assertEqual(verifier.can_sign(), False)
111
112
113 class FIPS_PKCS1_Verify_Tests_KAT(unittest.TestCase):
114 pass
115
116
117 test_vectors_verify = load_test_vectors(("Signature", "PKCS1-PSS"),
118 "SigVerPSS_186-3.rsp",
119 "Signature Verification 186-3",
120 {'shaalg': lambda x: x,
121 'result': lambda x: x}) or []
122
123
124 for count, tv in enumerate(test_vectors_verify):
125 if isinstance(tv, str):
126 continue
127 if hasattr(tv, "n"):
128 modulus = tv.n
129 continue
130 if hasattr(tv, "p"):
131 continue
132
133 hash_module = load_hash_by_name(tv.shaalg.upper())
134 hash_obj = hash_module.new(tv.msg)
135 public_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e)]) # type: ignore
136 if tv.saltval != b("\x00"):
137 prng = PRNG(tv.saltval)
138 verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng)
139 else:
140 verifier = pss.new(public_key, salt_bytes=0)
141
142 def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
143 verifier.verify(hash_obj, signature)
144
145 def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
146 self.assertRaises(ValueError, verifier.verify, hash_obj, signature)
147
148 if tv.result == 'p':
149 setattr(FIPS_PKCS1_Verify_Tests_KAT, "test_positive_%d" % count, positive_test)
150 else:
151 setattr(FIPS_PKCS1_Verify_Tests_KAT, "test_negative_%d" % count, negative_test)
152
153
154 class FIPS_PKCS1_Sign_Tests(unittest.TestCase):
155
156 def shortDescription(self):
157 return "FIPS PKCS1 Tests (Sign)"
158
159 def test_can_sign(self):
160 test_private_key = RSA.generate(1024)
161 signer = pss.new(test_private_key)
162 self.assertEqual(signer.can_sign(), True)
163
164
165 class FIPS_PKCS1_Sign_Tests_KAT(unittest.TestCase):
166 pass
167
168
169 test_vectors_sign = load_test_vectors(("Signature", "PKCS1-PSS"),
170 "SigGenPSS_186-2.txt",
171 "Signature Generation 186-2",
172 {'shaalg': lambda x: x}) or []
173
174 test_vectors_sign += load_test_vectors(("Signature", "PKCS1-PSS"),
175 "SigGenPSS_186-3.txt",
176 "Signature Generation 186-3",
177 {'shaalg': lambda x: x}) or []
178
179 for count, tv in enumerate(test_vectors_sign):
180 if isinstance(tv, str):
181 continue
182 if hasattr(tv, "n"):
183 modulus = tv.n
184 continue
185 if hasattr(tv, "e"):
186 private_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e, tv.d)]) # type: ignore
187 continue
188
189 hash_module = load_hash_by_name(tv.shaalg.upper())
190 hash_obj = hash_module.new(tv.msg)
191 if tv.saltval != b("\x00"):
192 prng = PRNG(tv.saltval)
193 signer = pss.new(private_key, salt_bytes=len(tv.saltval), rand_func=prng)
194 else:
195 signer = pss.new(private_key, salt_bytes=0)
196
197 def new_test(self, hash_obj=hash_obj, signer=signer, result=tv.s):
198 signature = signer.sign(hash_obj)
199 self.assertEqual(signature, result)
200
201 setattr(FIPS_PKCS1_Sign_Tests_KAT, "test_%d" % count, new_test)
202
203
204 class PKCS1_Legacy_Module_Tests(unittest.TestCase):
205 """Verify that the legacy module Crypto.Signature.PKCS1_PSS
206 behaves as expected. The only difference is that the verify()
207 method returns True/False and does not raise exceptions."""
208
209 def shortDescription(self):
210 return "Test legacy Crypto.Signature.PKCS1_PSS"
211
212 def runTest(self):
213 key = RSA.generate(1024)
214 hashed = SHA1.new(b("Test"))
215 good_signature = PKCS1_PSS.new(key).sign(hashed)
216 verifier = PKCS1_PSS.new(key.public_key())
217
218 self.assertEqual(verifier.verify(hashed, good_signature), True)
219
220 # Flip a few bits in the signature
221 bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
222 self.assertEqual(verifier.verify(hashed, bad_signature), False)
223
224
225 class PKCS1_All_Hashes_Tests(unittest.TestCase):
226
227 def shortDescription(self):
228 return "Test PKCS#1 PSS signature in combination with all hashes"
229
230 def runTest(self):
231
232 key = RSA.generate(1280)
233 signer = pss.new(key)
234 hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
235 "SHA224", "SHA256", "SHA384", "SHA512",
236 "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")
237
238 for name in hash_names:
239 hashed = load_hash_by_name(name).new(b("Test"))
240 signer.sign(hashed)
241
242 from Crypto.Hash import BLAKE2b, BLAKE2s
243 for hash_size in (20, 32, 48, 64):
244 hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
245 signer.sign(hashed_b)
246 for hash_size in (16, 20, 28, 32):
247 hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
248 signer.sign(hashed_s)
249
250
251 def get_hash_module(hash_name):
252 if hash_name == "SHA-512":
253 hash_module = SHA512
254 elif hash_name == "SHA-512/224":
255 hash_module = SHA512.new(truncate="224")
256 elif hash_name == "SHA-512/256":
257 hash_module = SHA512.new(truncate="256")
258 elif hash_name == "SHA-384":
259 hash_module = SHA384
260 elif hash_name == "SHA-256":
261 hash_module = SHA256
262 elif hash_name == "SHA-224":
263 hash_module = SHA224
264 elif hash_name == "SHA-1":
265 hash_module = SHA1
266 else:
267 raise ValueError("Unknown hash algorithm: " + hash_name)
268 return hash_module
269
270
271 class TestVectorsPSSWycheproof(unittest.TestCase):
272
273 def __init__(self, wycheproof_warnings):
274 unittest.TestCase.__init__(self)
275 self._wycheproof_warnings = wycheproof_warnings
276 self._id = "None"
277
278 def add_tests(self, filename):
279
280 def filter_rsa(group):
281 return RSA.import_key(group['keyPem'])
282
283 def filter_sha(group):
284 return get_hash_module(group['sha'])
285
286 def filter_type(group):
287 type_name = group['type']
288 if type_name not in ("RsassaPssVerify", ):
289 raise ValueError("Unknown type name " + type_name)
290
291 def filter_slen(group):
292 return group['sLen']
293
294 def filter_mgf(group):
295 mgf = group['mgf']
296 if mgf not in ("MGF1", ):
297 raise ValueError("Unknown MGF " + mgf)
298 mgf1_hash = get_hash_module(group['mgfSha'])
299
300 def mgf(x, y, mh=mgf1_hash):
301 return MGF1(x, y, mh)
302
303 return mgf
304
305 result = load_test_vectors_wycheproof(("Signature", "wycheproof"),
306 filename,
307 "Wycheproof PSS signature (%s)" % filename,
308 group_tag={'key': filter_rsa,
309 'hash_module': filter_sha,
310 'sLen': filter_slen,
311 'mgf': filter_mgf,
312 'type': filter_type})
313 return result
314
315 def setUp(self):
316 self.tv = []
317 self.add_tests("rsa_pss_2048_sha1_mgf1_20_test.json")
318 self.add_tests("rsa_pss_2048_sha256_mgf1_0_test.json")
319 self.add_tests("rsa_pss_2048_sha256_mgf1_32_test.json")
320 self.add_tests("rsa_pss_2048_sha512_256_mgf1_28_test.json")
321 self.add_tests("rsa_pss_2048_sha512_256_mgf1_32_test.json")
322 self.add_tests("rsa_pss_3072_sha256_mgf1_32_test.json")
323 self.add_tests("rsa_pss_4096_sha256_mgf1_32_test.json")
324 self.add_tests("rsa_pss_4096_sha512_mgf1_32_test.json")
325 self.add_tests("rsa_pss_misc_test.json")
326
327 def shortDescription(self):
328 return self._id
329
330 def warn(self, tv):
331 if tv.warning and self._wycheproof_warnings:
332 import warnings
333 warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
334
335 def test_verify(self, tv):
336 self._id = "Wycheproof RSA PSS Test #%d (%s)" % (tv.id, tv.comment)
337
338 hashed_msg = tv.hash_module.new(tv.msg)
339 signer = pss.new(tv.key, mask_func=tv.mgf, salt_bytes=tv.sLen)
340 try:
341 signature = signer.verify(hashed_msg, tv.sig)
342 except ValueError as e:
343 if tv.warning:
344 return
345 assert not tv.valid
346 else:
347 assert tv.valid
348 self.warn(tv)
349
350 def runTest(self):
351 for tv in self.tv:
352 self.test_verify(tv)
353
354
355 def get_tests(config={}):
356 wycheproof_warnings = config.get('wycheproof_warnings')
357
358 tests = []
359 tests += list_test_cases(PSS_Tests)
360 tests += list_test_cases(FIPS_PKCS1_Verify_Tests)
361 tests += list_test_cases(FIPS_PKCS1_Sign_Tests)
362 tests += list_test_cases(PKCS1_Legacy_Module_Tests)
363 tests += list_test_cases(PKCS1_All_Hashes_Tests)
364
365 if config.get('slow_tests'):
366 tests += list_test_cases(FIPS_PKCS1_Verify_Tests_KAT)
367 tests += list_test_cases(FIPS_PKCS1_Sign_Tests_KAT)
368
369 tests += [TestVectorsPSSWycheproof(wycheproof_warnings)]
370
371 return tests
372
373
374 if __name__ == '__main__':
375 def suite():
376 return unittest.TestSuite(get_tests())
377 unittest.main(defaultTest='suite')