test_pkcs1_15.py 12 KB

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