test_pss.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 unittest
  31. from Crypto.Util.py3compat import b, bchr
  32. from Crypto.Util.number import bytes_to_long
  33. from Crypto.Util.strxor import strxor
  34. from Crypto.SelfTest.st_common import list_test_cases
  35. from Crypto.SelfTest.loader import load_tests
  36. from Crypto.Hash import SHA1
  37. from Crypto.PublicKey import RSA
  38. from Crypto.Signature import pss
  39. from Crypto.Signature import PKCS1_PSS
  40. def load_hash_by_name(hash_name):
  41. return __import__("Crypto.Hash." + hash_name, globals(), locals(), ["new"])
  42. class PRNG(object):
  43. def __init__(self, stream):
  44. self.stream = stream
  45. self.idx = 0
  46. def __call__(self, rnd_size):
  47. result = self.stream[self.idx:self.idx + rnd_size]
  48. self.idx += rnd_size
  49. return result
  50. class FIPS_PKCS1_Verify_Tests(unittest.TestCase):
  51. def shortDescription(self):
  52. return "FIPS PKCS1 Tests (Verify)"
  53. def verify_positive(self, hashmod, message, public_key, salt, signature):
  54. prng = PRNG(salt)
  55. hashed = hashmod.new(message)
  56. verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng)
  57. verifier.verify(hashed, signature)
  58. def verify_negative(self, hashmod, message, public_key, salt, signature):
  59. prng = PRNG(salt)
  60. hashed = hashmod.new(message)
  61. verifier = pss.new(public_key, salt_bytes=len(salt), rand_func=prng)
  62. self.assertRaises(ValueError, verifier.verify, hashed, signature)
  63. def test_can_sign(self):
  64. test_public_key = RSA.generate(1024).publickey()
  65. verifier = pss.new(test_public_key)
  66. self.assertEqual(verifier.can_sign(), False)
  67. test_vectors_verify = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-PSS"),
  68. "SigVerPSS_186-3.rsp",
  69. "Signature Verification 186-3",
  70. { 'shaalg' : lambda x: x,
  71. 'result' : lambda x: x })
  72. for count, tv in enumerate(test_vectors_verify):
  73. if isinstance(tv, basestring):
  74. continue
  75. if hasattr(tv, "n"):
  76. modulus = tv.n
  77. continue
  78. if hasattr(tv, "p"):
  79. continue
  80. hash_module = load_hash_by_name(tv.shaalg.upper())
  81. hash_obj = hash_module.new(tv.msg)
  82. public_key = RSA.construct([bytes_to_long(x) for x in modulus, tv.e])
  83. if tv.saltval != b("\x00"):
  84. prng = PRNG(tv.saltval)
  85. verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng)
  86. else:
  87. verifier = pss.new(public_key, salt_bytes=0)
  88. def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
  89. verifier.verify(hash_obj, signature)
  90. def negative_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s):
  91. self.assertRaises(ValueError, verifier.verify, hash_obj, signature)
  92. if tv.result == 'p':
  93. setattr(FIPS_PKCS1_Verify_Tests, "test_positive_%d" % count, positive_test)
  94. else:
  95. setattr(FIPS_PKCS1_Verify_Tests, "test_negative_%d" % count, negative_test)
  96. class FIPS_PKCS1_Sign_Tests(unittest.TestCase):
  97. def shortDescription(self):
  98. return "FIPS PKCS1 Tests (Sign)"
  99. def test_can_sign(self):
  100. test_private_key = RSA.generate(1024)
  101. signer = pss.new(test_private_key)
  102. self.assertEqual(signer.can_sign(), True)
  103. test_vectors_sign = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-PSS"),
  104. "SigGenPSS_186-2.txt",
  105. "Signature Generation 186-2",
  106. { 'shaalg' : lambda x: x })
  107. test_vectors_sign += load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "PKCS1-PSS"),
  108. "SigGenPSS_186-3.txt",
  109. "Signature Generation 186-3",
  110. { 'shaalg' : lambda x: x })
  111. for count, tv in enumerate(test_vectors_sign):
  112. if isinstance(tv, basestring):
  113. continue
  114. if hasattr(tv, "n"):
  115. modulus = tv.n
  116. continue
  117. if hasattr(tv, "e"):
  118. private_key = RSA.construct([bytes_to_long(x) for x in modulus, tv.e, tv.d])
  119. continue
  120. hash_module = load_hash_by_name(tv.shaalg.upper())
  121. hash_obj = hash_module.new(tv.msg)
  122. if tv.saltval != b("\x00"):
  123. prng = PRNG(tv.saltval)
  124. signer = pss.new(private_key, salt_bytes=len(tv.saltval), rand_func=prng)
  125. else:
  126. signer = pss.new(private_key, salt_bytes=0)
  127. def new_test(self, hash_obj=hash_obj, signer=signer, result=tv.s):
  128. signature = signer.sign(hash_obj)
  129. self.assertEqual(signature, result)
  130. setattr(FIPS_PKCS1_Sign_Tests, "test_%d" % count, new_test)
  131. class PKCS1_Legacy_Module_Tests(unittest.TestCase):
  132. """Verify that the legacy module Crypto.Signature.PKCS1_PSS
  133. behaves as expected. The only difference is that the verify()
  134. method returns True/False and does not raise exceptions."""
  135. def shortDescription(self):
  136. return "Test legacy Crypto.Signature.PKCS1_PSS"
  137. def runTest(self):
  138. key = RSA.generate(1024)
  139. hashed = SHA1.new(b("Test"))
  140. good_signature = PKCS1_PSS.new(key).sign(hashed)
  141. verifier = PKCS1_PSS.new(key.publickey())
  142. self.assertEqual(verifier.verify(hashed, good_signature), True)
  143. # Flip a few bits in the signature
  144. bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
  145. self.assertEqual(verifier.verify(hashed, bad_signature), False)
  146. class PKCS1_All_Hashes_Tests(unittest.TestCase):
  147. def shortDescription(self):
  148. return "Test PKCS#1 PSS signature in combination with all hashes"
  149. def runTest(self):
  150. key = RSA.generate(1280)
  151. signer = pss.new(key)
  152. hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
  153. "SHA224", "SHA256", "SHA384", "SHA512",
  154. "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")
  155. for name in hash_names:
  156. hashed = load_hash_by_name(name).new(b("Test"))
  157. signer.sign(hashed)
  158. from Crypto.Hash import BLAKE2b, BLAKE2s
  159. for hash_size in (20, 32, 48, 64):
  160. hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
  161. signer.sign(hashed_b)
  162. for hash_size in (16, 20, 28, 32):
  163. hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
  164. signer.sign(hashed_s)
  165. def get_tests(config={}):
  166. tests = []
  167. tests += list_test_cases(FIPS_PKCS1_Verify_Tests)
  168. tests += list_test_cases(FIPS_PKCS1_Sign_Tests)
  169. tests += list_test_cases(PKCS1_Legacy_Module_Tests)
  170. tests += list_test_cases(PKCS1_All_Hashes_Tests)
  171. return tests
  172. if __name__ == '__main__':
  173. suite = lambda: unittest.TestSuite(get_tests())
  174. unittest.main(defaultTest='suite')