PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/site-packages/Crypto/SelfTest/Signature/test_pkcs1_15.py

https://gitlab.com/abhi1tb/build
Python | 358 lines | 265 code | 62 blank | 31 comment | 40 complexity | 37fb3227c6b083b1d9c2444cf917ca2a MD5 | raw file
  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_tests
  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).publickey()
  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_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "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 })
  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_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-v1.5"),
  90. "SigGen15_186-2.txt",
  91. "Signature Generation 186-2",
  92. { 'shaalg' : lambda x: x })
  93. test_vectors_sign += load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-v1.5"),
  94. "SigGen15_186-3.txt",
  95. "Signature Generation 186-3",
  96. { 'shaalg' : lambda x: x })
  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.publickey())
  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. comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
  201. with open(pycryptodome_filename(comps, filename), "rt") as file_in:
  202. tv_tree = json.load(file_in)
  203. class TestVector(object):
  204. pass
  205. self.tv = []
  206. for group in tv_tree['testGroups']:
  207. key = RSA.import_key(group['keyPem'])
  208. hash_name = group['sha']
  209. if hash_name == "SHA-512":
  210. hash_module = SHA512
  211. elif hash_name == "SHA-512/224":
  212. hash_module = SHA512.new(truncate="224")
  213. elif hash_name == "SHA-512/256":
  214. hash_module = SHA512.new(truncate="256")
  215. elif hash_name == "SHA3-512":
  216. hash_module = SHA3_512
  217. elif hash_name == "SHA-384":
  218. hash_module = SHA384
  219. elif hash_name == "SHA3-384":
  220. hash_module = SHA3_384
  221. elif hash_name == "SHA-256":
  222. hash_module = SHA256
  223. elif hash_name == "SHA3-256":
  224. hash_module = SHA3_256
  225. elif hash_name == "SHA-224":
  226. hash_module = SHA224
  227. elif hash_name == "SHA3-224":
  228. hash_module = SHA3_224
  229. elif hash_name == "SHA-1":
  230. hash_module = SHA1
  231. else:
  232. raise ValueError("Unknown hash algorithm: " + hash_name)
  233. type_name = group['type']
  234. if type_name not in ("RsassaPkcs1Verify", "RsassaPkcs1Generate"):
  235. raise ValueError("Unknown type name " + type_name)
  236. for test in group['tests']:
  237. tv = TestVector()
  238. tv.id = test['tcId']
  239. tv.comment = test['comment']
  240. for attr in 'msg', 'sig':
  241. setattr(tv, attr, unhexlify(test[attr]))
  242. tv.key = key
  243. tv.hash_module = hash_module
  244. tv.valid = test['result'] != "invalid"
  245. tv.warning = test['result'] == "acceptable"
  246. self.tv.append(tv)
  247. def shortDescription(self):
  248. return self._id
  249. def warn(self, tv):
  250. if tv.warning and self._wycheproof_warnings:
  251. import warnings
  252. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  253. def test_verify(self, tv):
  254. self._id = "Wycheproof RSA PKCS$#1 Test #" + str(tv.id)
  255. hashed_msg = tv.hash_module.new(tv.msg)
  256. signer = pkcs1_15.new(tv.key)
  257. try:
  258. signature = signer.verify(hashed_msg, tv.sig)
  259. except ValueError as e:
  260. if tv.warning:
  261. return
  262. assert not tv.valid
  263. else:
  264. assert tv.valid
  265. self.warn(tv)
  266. def runTest(self):
  267. for tv in self.tv:
  268. self.test_verify(tv)
  269. def get_tests(config={}):
  270. wycheproof_warnings = config.get('wycheproof_warnings')
  271. tests = []
  272. tests += list_test_cases(FIPS_PKCS1_Verify_Tests)
  273. tests += list_test_cases(FIPS_PKCS1_Sign_Tests)
  274. tests += list_test_cases(PKCS1_15_NoParams)
  275. tests += list_test_cases(PKCS1_Legacy_Module_Tests)
  276. tests += list_test_cases(PKCS1_All_Hashes_Tests)
  277. tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
  278. if config.get('slow_tests'):
  279. tests += list_test_cases(FIPS_PKCS1_Verify_Tests_KAT)
  280. tests += list_test_cases(FIPS_PKCS1_Sign_Tests_KAT)
  281. return tests
  282. if __name__ == '__main__':
  283. suite = lambda: unittest.TestSuite(get_tests())
  284. unittest.main(defaultTest='suite')