test_DSA.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # -*- coding: utf-8 -*-
  2. #
  3. # SelfTest/PublicKey/test_DSA.py: Self-test for the DSA primitive
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. """Self-test suite for Cryptodome.PublicKey.DSA"""
  25. import os
  26. from Cryptodome.Util.py3compat import *
  27. import unittest
  28. from Cryptodome.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
  29. def _sws(s):
  30. """Remove whitespace from a text or byte string"""
  31. if isinstance(s,str):
  32. return "".join(s.split())
  33. else:
  34. return b("").join(s.split())
  35. class DSATest(unittest.TestCase):
  36. # Test vector from "Appendix 5. Example of the DSA" of
  37. # "Digital Signature Standard (DSS)",
  38. # U.S. Department of Commerce/National Institute of Standards and Technology
  39. # FIPS 186-2 (+Change Notice), 2000 January 27.
  40. # http://csrc.nist.gov/publications/fips/fips186-2/fips186-2-change1.pdf
  41. y = _sws("""19131871 d75b1612 a819f29d 78d1b0d7 346f7aa7 7bb62a85
  42. 9bfd6c56 75da9d21 2d3a36ef 1672ef66 0b8c7c25 5cc0ec74
  43. 858fba33 f44c0669 9630a76b 030ee333""")
  44. g = _sws("""626d0278 39ea0a13 413163a5 5b4cb500 299d5522 956cefcb
  45. 3bff10f3 99ce2c2e 71cb9de5 fa24babf 58e5b795 21925c9c
  46. c42e9f6f 464b088c c572af53 e6d78802""")
  47. p = _sws("""8df2a494 492276aa 3d25759b b06869cb eac0d83a fb8d0cf7
  48. cbb8324f 0d7882e5 d0762fc5 b7210eaf c2e9adac 32ab7aac
  49. 49693dfb f83724c2 ec0736ee 31c80291""")
  50. q = _sws("""c773218c 737ec8ee 993b4f2d ed30f48e dace915f""")
  51. x = _sws("""2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614""")
  52. k = _sws("""358dad57 1462710f 50e254cf 1a376b2b deaadfbf""")
  53. k_inverse = _sws("""0d516729 8202e49b 4116ac10 4fc3f415 ae52f917""")
  54. m = b2a_hex(b("abc"))
  55. m_hash = _sws("""a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d""")
  56. r = _sws("""8bac1ab6 6410435c b7181f95 b16ab97c 92b341c0""")
  57. s = _sws("""41e2345f 1f56df24 58f426d1 55b4ba2d b6dcd8c8""")
  58. def setUp(self):
  59. global DSA, Random, bytes_to_long, size
  60. from Cryptodome.PublicKey import DSA
  61. from Cryptodome import Random
  62. from Cryptodome.Util.number import bytes_to_long, inverse, size
  63. self.dsa = DSA
  64. def test_generate_1arg(self):
  65. """DSA (default implementation) generated key (1 argument)"""
  66. dsaObj = self.dsa.generate(1024)
  67. self._check_private_key(dsaObj)
  68. pub = dsaObj.public_key()
  69. self._check_public_key(pub)
  70. def test_generate_2arg(self):
  71. """DSA (default implementation) generated key (2 arguments)"""
  72. dsaObj = self.dsa.generate(1024, Random.new().read)
  73. self._check_private_key(dsaObj)
  74. pub = dsaObj.public_key()
  75. self._check_public_key(pub)
  76. def test_construct_4tuple(self):
  77. """DSA (default implementation) constructed key (4-tuple)"""
  78. (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
  79. dsaObj = self.dsa.construct((y, g, p, q))
  80. self._test_verification(dsaObj)
  81. def test_construct_5tuple(self):
  82. """DSA (default implementation) constructed key (5-tuple)"""
  83. (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
  84. dsaObj = self.dsa.construct((y, g, p, q, x))
  85. self._test_signing(dsaObj)
  86. self._test_verification(dsaObj)
  87. def test_construct_bad_key4(self):
  88. (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
  89. tup = (y, g, p+1, q)
  90. self.assertRaises(ValueError, self.dsa.construct, tup)
  91. tup = (y, g, p, q+1)
  92. self.assertRaises(ValueError, self.dsa.construct, tup)
  93. tup = (y, 1, p, q)
  94. self.assertRaises(ValueError, self.dsa.construct, tup)
  95. def test_construct_bad_key5(self):
  96. (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
  97. tup = (y, g, p, q, x+1)
  98. self.assertRaises(ValueError, self.dsa.construct, tup)
  99. tup = (y, g, p, q, q+10)
  100. self.assertRaises(ValueError, self.dsa.construct, tup)
  101. def _check_private_key(self, dsaObj):
  102. # Check capabilities
  103. self.assertEqual(1, dsaObj.has_private())
  104. self.assertEqual(1, dsaObj.can_sign())
  105. self.assertEqual(0, dsaObj.can_encrypt())
  106. # Sanity check key data
  107. self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
  108. self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
  109. self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
  110. self.assertEqual(dsaObj.y, pow(dsaObj.g, dsaObj.x, dsaObj.p)) # y == g**x mod p
  111. self.assertEqual(1, 0 < dsaObj.x < dsaObj.q) # 0 < x < q
  112. def _check_public_key(self, dsaObj):
  113. k = bytes_to_long(a2b_hex(self.k))
  114. m_hash = bytes_to_long(a2b_hex(self.m_hash))
  115. # Check capabilities
  116. self.assertEqual(0, dsaObj.has_private())
  117. self.assertEqual(1, dsaObj.can_sign())
  118. self.assertEqual(0, dsaObj.can_encrypt())
  119. # Check that private parameters are all missing
  120. self.assertEqual(0, hasattr(dsaObj, 'x'))
  121. # Sanity check key data
  122. self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
  123. self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
  124. self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
  125. # Public-only key objects should raise an error when .sign() is called
  126. self.assertRaises(TypeError, dsaObj._sign, m_hash, k)
  127. # Check __eq__ and __ne__
  128. self.assertEqual(dsaObj.public_key() == dsaObj.public_key(),True) # assert_
  129. self.assertEqual(dsaObj.public_key() != dsaObj.public_key(),False) # failIf
  130. self.assertEqual(dsaObj.public_key(), dsaObj.publickey())
  131. def _test_signing(self, dsaObj):
  132. k = bytes_to_long(a2b_hex(self.k))
  133. m_hash = bytes_to_long(a2b_hex(self.m_hash))
  134. r = bytes_to_long(a2b_hex(self.r))
  135. s = bytes_to_long(a2b_hex(self.s))
  136. (r_out, s_out) = dsaObj._sign(m_hash, k)
  137. self.assertEqual((r, s), (r_out, s_out))
  138. def _test_verification(self, dsaObj):
  139. m_hash = bytes_to_long(a2b_hex(self.m_hash))
  140. r = bytes_to_long(a2b_hex(self.r))
  141. s = bytes_to_long(a2b_hex(self.s))
  142. self.failUnless(dsaObj._verify(m_hash, (r, s)))
  143. self.failIf(dsaObj._verify(m_hash + 1, (r, s)))
  144. def test_repr(self):
  145. (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
  146. dsaObj = self.dsa.construct((y, g, p, q))
  147. repr(dsaObj)
  148. class DSADomainTest(unittest.TestCase):
  149. def test_domain1(self):
  150. """Verify we can generate new keys in a given domain"""
  151. dsa_key_1 = DSA.generate(1024)
  152. domain_params = dsa_key_1.domain()
  153. dsa_key_2 = DSA.generate(1024, domain=domain_params)
  154. self.assertEqual(dsa_key_1.p, dsa_key_2.p)
  155. self.assertEqual(dsa_key_1.q, dsa_key_2.q)
  156. self.assertEqual(dsa_key_1.g, dsa_key_2.g)
  157. self.assertEqual(dsa_key_1.domain(), dsa_key_2.domain())
  158. def _get_weak_domain(self):
  159. from Cryptodome.Math.Numbers import Integer
  160. from Cryptodome.Math import Primality
  161. p = Integer(4)
  162. while p.size_in_bits() != 1024 or Primality.test_probable_prime(p) != Primality.PROBABLY_PRIME:
  163. q1 = Integer.random(exact_bits=80)
  164. q2 = Integer.random(exact_bits=80)
  165. q = q1 * q2
  166. z = Integer.random(exact_bits=1024-160)
  167. p = z * q + 1
  168. h = Integer(2)
  169. g = 1
  170. while g == 1:
  171. g = pow(h, z, p)
  172. h += 1
  173. return (p, q, g)
  174. def test_generate_error_weak_domain(self):
  175. """Verify that domain parameters with composite q are rejected"""
  176. domain_params = self._get_weak_domain()
  177. self.assertRaises(ValueError, DSA.generate, 1024, domain=domain_params)
  178. def test_construct_error_weak_domain(self):
  179. """Verify that domain parameters with composite q are rejected"""
  180. from Cryptodome.Math.Numbers import Integer
  181. p, q, g = self._get_weak_domain()
  182. y = pow(g, 89, p)
  183. self.assertRaises(ValueError, DSA.construct, (y, g, p, q))
  184. def get_tests(config={}):
  185. tests = []
  186. tests += list_test_cases(DSATest)
  187. tests += list_test_cases(DSADomainTest)
  188. return tests
  189. if __name__ == '__main__':
  190. suite = lambda: unittest.TestSuite(get_tests())
  191. unittest.main(defaultTest='suite')
  192. # vim:set ts=4 sw=4 sts=4 expandtab: