test_pkcs1_15.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  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. import json
  31. import unittest
  32. from binascii import unhexlify
  33. from Crypto.Util.py3compat import 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. from Crypto.Hash import (SHA1, SHA224, SHA256, SHA384, SHA512, SHA3_384,
  39. SHA3_224, SHA3_256, SHA3_512)
  40. from Crypto.PublicKey import RSA
  41. from Crypto.Signature import pkcs1_15
  42. from Crypto.Signature import PKCS1_v1_5
  43. from Crypto.Util._file_system import pycryptodome_filename
  44. from Crypto.Util.strxor import strxor
  45. def load_hash_by_name(hash_name):
  46. return __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"])
  47. class FIPS_PKCS1_Verify_Tests(unittest.TestCase):
  48. def shortDescription(self):
  49. return "FIPS PKCS1 Tests (Verify)"
  50. def test_can_sign(self):
  51. test_public_key = RSA.generate(1024).public_key()
  52. verifier = pkcs1_15.new(test_public_key)
  53. self.assertEqual(verifier.can_sign(), False)
  54. class FIPS_PKCS1_Verify_Tests_KAT(unittest.TestCase):
  55. pass
  56. test_vectors_verify = load_test_vectors(("Signature", "PKCS1-v1.5"),
  57. "SigVer15_186-3.rsp",
  58. "Signature Verification 186-3",
  59. {'shaalg': lambda x: x,
  60. 'd': lambda x: int(x),
  61. 'result': lambda x: x}) or []
  62. for count, tv in enumerate(test_vectors_verify):
  63. if isinstance(tv, str):
  64. continue
  65. if hasattr(tv, "n"):
  66. modulus = tv.n
  67. continue
  68. hash_module = load_hash_by_name(tv.shaalg.upper())
  69. hash_obj = hash_module.new(tv.msg)
  70. public_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e)]) # type: ignore
  71. verifier = pkcs1_15.new(public_key)
  72. def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
  73. verifier.verify(hash_obj, signature)
  74. def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
  75. self.assertRaises(ValueError, verifier.verify, hash_obj, signature)
  76. if tv.result == 'f':
  77. setattr(FIPS_PKCS1_Verify_Tests_KAT, "test_negative_%d" % count, negative_test)
  78. else:
  79. setattr(FIPS_PKCS1_Verify_Tests_KAT, "test_positive_%d" % count, positive_test)
  80. class FIPS_PKCS1_Sign_Tests(unittest.TestCase):
  81. def shortDescription(self):
  82. return "FIPS PKCS1 Tests (Sign)"
  83. def test_can_sign(self):
  84. test_private_key = RSA.generate(1024)
  85. signer = pkcs1_15.new(test_private_key)
  86. self.assertEqual(signer.can_sign(), True)
  87. class FIPS_PKCS1_Sign_Tests_KAT(unittest.TestCase):
  88. pass
  89. test_vectors_sign = load_test_vectors(("Signature", "PKCS1-v1.5"),
  90. "SigGen15_186-2.txt",
  91. "Signature Generation 186-2",
  92. {'shaalg': lambda x: x}) or []
  93. test_vectors_sign += load_test_vectors(("Signature", "PKCS1-v1.5"),
  94. "SigGen15_186-3.txt",
  95. "Signature Generation 186-3",
  96. {'shaalg': lambda x: x}) or []
  97. for count, tv in enumerate(test_vectors_sign):
  98. if isinstance(tv, str):
  99. continue
  100. if hasattr(tv, "n"):
  101. modulus = tv.n
  102. continue
  103. if hasattr(tv, "e"):
  104. private_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e, tv.d)]) # type: ignore
  105. signer = pkcs1_15.new(private_key)
  106. continue
  107. hash_module = load_hash_by_name(tv.shaalg.upper())
  108. hash_obj = hash_module.new(tv.msg)
  109. def new_test(self, hash_obj=hash_obj, signer=signer, result=tv.s):
  110. signature = signer.sign(hash_obj)
  111. self.assertEqual(signature, result)
  112. setattr(FIPS_PKCS1_Sign_Tests_KAT, "test_%d" % count, new_test)
  113. class PKCS1_15_NoParams(unittest.TestCase):
  114. """Verify that PKCS#1 v1.5 signatures pass even without NULL parameters in
  115. the algorithm identifier (PyCrypto/LP bug #1119552)."""
  116. rsakey = """-----BEGIN RSA PRIVATE KEY-----
  117. MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII
  118. q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8
  119. Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI
  120. OQIhAPIPLz4dphiD9imAkivY31Rc5AfHJiQRA7XixTcjEkojAiEAyh/pJHks/Mlr
  121. +rdPNEpotBjfV4M4BkgGAA/ipcmaAjcCIQCHvhwwKVBLzzTscT2HeUdEeBMoiXXK
  122. JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9
  123. n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ==
  124. -----END RSA PRIVATE KEY-----"""
  125. msg = b"This is a test\x0a"
  126. # PKCS1 v1.5 signature of the message computed using SHA-1.
  127. # The digestAlgorithm SEQUENCE does NOT contain the NULL parameter.
  128. sig_str = "a287a13517f716e72fb14eea8e33a8db4a4643314607e7ca3e3e28"\
  129. "1893db74013dda8b855fd99f6fecedcb25fcb7a434f35cd0a101f8"\
  130. "b19348e0bd7b6f152dfc"
  131. signature = unhexlify(sig_str)
  132. def runTest(self):
  133. verifier = pkcs1_15.new(RSA.importKey(self.rsakey))
  134. hashed = SHA1.new(self.msg)
  135. verifier.verify(hashed, self.signature)
  136. class PKCS1_Legacy_Module_Tests(unittest.TestCase):
  137. """Verify that the legacy module Crypto.Signature.PKCS1_v1_5
  138. behaves as expected. The only difference is that the verify()
  139. method returns True/False and does not raise exceptions."""
  140. def shortDescription(self):
  141. return "Test legacy Crypto.Signature.PKCS1_v1_5"
  142. def runTest(self):
  143. key = RSA.importKey(PKCS1_15_NoParams.rsakey)
  144. hashed = SHA1.new(b"Test")
  145. good_signature = PKCS1_v1_5.new(key).sign(hashed)
  146. verifier = PKCS1_v1_5.new(key.public_key())
  147. self.assertEqual(verifier.verify(hashed, good_signature), True)
  148. # Flip a few bits in the signature
  149. bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
  150. self.assertEqual(verifier.verify(hashed, bad_signature), False)
  151. class PKCS1_All_Hashes_Tests(unittest.TestCase):
  152. def shortDescription(self):
  153. return "Test PKCS#1v1.5 signature in combination with all hashes"
  154. def runTest(self):
  155. key = RSA.generate(1024)
  156. signer = pkcs1_15.new(key)
  157. hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
  158. "SHA224", "SHA256", "SHA384", "SHA512",
  159. "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")
  160. for name in hash_names:
  161. hashed = load_hash_by_name(name).new(b"Test")
  162. signer.sign(hashed)
  163. from Crypto.Hash import BLAKE2b, BLAKE2s
  164. for hash_size in (20, 32, 48, 64):
  165. hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b"Test")
  166. signer.sign(hashed_b)
  167. for hash_size in (16, 20, 28, 32):
  168. hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b"Test")
  169. signer.sign(hashed_s)
  170. class TestVectorsWycheproof(unittest.TestCase):
  171. def __init__(self, wycheproof_warnings):
  172. unittest.TestCase.__init__(self)
  173. self._wycheproof_warnings = wycheproof_warnings
  174. self._id = "None"
  175. def setUp(self):
  176. self.tv = []
  177. self.add_tests("rsa_sig_gen_misc_test.json")
  178. self.add_tests("rsa_signature_2048_sha224_test.json")
  179. self.add_tests("rsa_signature_2048_sha256_test.json")
  180. self.add_tests("rsa_signature_2048_sha384_test.json")
  181. self.add_tests("rsa_signature_2048_sha3_224_test.json")
  182. self.add_tests("rsa_signature_2048_sha3_256_test.json")
  183. self.add_tests("rsa_signature_2048_sha3_384_test.json")
  184. self.add_tests("rsa_signature_2048_sha3_512_test.json")
  185. self.add_tests("rsa_signature_2048_sha512_test.json")
  186. self.add_tests("rsa_signature_2048_sha512_224_test.json")
  187. self.add_tests("rsa_signature_2048_sha512_256_test.json")
  188. self.add_tests("rsa_signature_3072_sha256_test.json")
  189. self.add_tests("rsa_signature_3072_sha384_test.json")
  190. self.add_tests("rsa_signature_3072_sha3_256_test.json")
  191. self.add_tests("rsa_signature_3072_sha3_384_test.json")
  192. self.add_tests("rsa_signature_3072_sha3_512_test.json")
  193. self.add_tests("rsa_signature_3072_sha512_test.json")
  194. self.add_tests("rsa_signature_3072_sha512_256_test.json")
  195. self.add_tests("rsa_signature_4096_sha384_test.json")
  196. self.add_tests("rsa_signature_4096_sha512_test.json")
  197. self.add_tests("rsa_signature_4096_sha512_256_test.json")
  198. self.add_tests("rsa_signature_test.json")
  199. def add_tests(self, filename):
  200. def filter_rsa(group):
  201. return RSA.import_key(group['keyPem'])
  202. def filter_sha(group):
  203. hash_name = group['sha']
  204. if hash_name == "SHA-512":
  205. return SHA512
  206. elif hash_name == "SHA-512/224":
  207. return SHA512.new(truncate="224")
  208. elif hash_name == "SHA-512/256":
  209. return SHA512.new(truncate="256")
  210. elif hash_name == "SHA3-512":
  211. return SHA3_512
  212. elif hash_name == "SHA-384":
  213. return SHA384
  214. elif hash_name == "SHA3-384":
  215. return SHA3_384
  216. elif hash_name == "SHA-256":
  217. return SHA256
  218. elif hash_name == "SHA3-256":
  219. return SHA3_256
  220. elif hash_name == "SHA-224":
  221. return SHA224
  222. elif hash_name == "SHA3-224":
  223. return SHA3_224
  224. elif hash_name == "SHA-1":
  225. return SHA1
  226. else:
  227. raise ValueError("Unknown hash algorithm: " + hash_name)
  228. def filter_type(group):
  229. type_name = group['type']
  230. if type_name not in ("RsassaPkcs1Verify", "RsassaPkcs1Generate"):
  231. raise ValueError("Unknown type name " + type_name)
  232. result = load_test_vectors_wycheproof(("Signature", "wycheproof"),
  233. filename,
  234. "Wycheproof PKCS#1v1.5 signature (%s)" % filename,
  235. group_tag={'rsa_key': filter_rsa,
  236. 'hash_mod': filter_sha,
  237. 'type': filter_type})
  238. return result
  239. def shortDescription(self):
  240. return self._id
  241. def warn(self, tv):
  242. if tv.warning and self._wycheproof_warnings:
  243. import warnings
  244. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  245. def test_verify(self, tv):
  246. self._id = "Wycheproof RSA PKCS$#1 Test #" + str(tv.id)
  247. hashed_msg = tv.hash_module.new(tv.msg)
  248. signer = pkcs1_15.new(tv.key)
  249. try:
  250. signature = signer.verify(hashed_msg, tv.sig)
  251. except ValueError as e:
  252. if tv.warning:
  253. return
  254. assert not tv.valid
  255. else:
  256. assert tv.valid
  257. self.warn(tv)
  258. def runTest(self):
  259. for tv in self.tv:
  260. self.test_verify(tv)
  261. def get_tests(config={}):
  262. wycheproof_warnings = config.get('wycheproof_warnings')
  263. tests = []
  264. tests += list_test_cases(FIPS_PKCS1_Verify_Tests)
  265. tests += list_test_cases(FIPS_PKCS1_Sign_Tests)
  266. tests += list_test_cases(PKCS1_15_NoParams)
  267. tests += list_test_cases(PKCS1_Legacy_Module_Tests)
  268. tests += list_test_cases(PKCS1_All_Hashes_Tests)
  269. tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
  270. if config.get('slow_tests'):
  271. tests += list_test_cases(FIPS_PKCS1_Verify_Tests_KAT)
  272. tests += list_test_cases(FIPS_PKCS1_Sign_Tests_KAT)
  273. return tests
  274. if __name__ == '__main__':
  275. suite = lambda: unittest.TestSuite(get_tests())
  276. unittest.main(defaultTest='suite')