test_DSA.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 Crypto.PublicKey.DSA"""
  25. __revision__ = "$Id$"
  26. import sys
  27. import os
  28. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  29. from Crypto.Util.py21compat import *
  30. from Crypto.Util.py3compat import *
  31. import unittest
  32. from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
  33. def _sws(s):
  34. """Remove whitespace from a text or byte string"""
  35. if isinstance(s,str):
  36. return "".join(s.split())
  37. else:
  38. return b("").join(s.split())
  39. class DSATest(unittest.TestCase):
  40. # Test vector from "Appendix 5. Example of the DSA" of
  41. # "Digital Signature Standard (DSS)",
  42. # U.S. Department of Commerce/National Institute of Standards and Technology
  43. # FIPS 186-2 (+Change Notice), 2000 January 27.
  44. # http://csrc.nist.gov/publications/fips/fips186-2/fips186-2-change1.pdf
  45. y = _sws("""19131871 d75b1612 a819f29d 78d1b0d7 346f7aa7 7bb62a85
  46. 9bfd6c56 75da9d21 2d3a36ef 1672ef66 0b8c7c25 5cc0ec74
  47. 858fba33 f44c0669 9630a76b 030ee333""")
  48. g = _sws("""626d0278 39ea0a13 413163a5 5b4cb500 299d5522 956cefcb
  49. 3bff10f3 99ce2c2e 71cb9de5 fa24babf 58e5b795 21925c9c
  50. c42e9f6f 464b088c c572af53 e6d78802""")
  51. p = _sws("""8df2a494 492276aa 3d25759b b06869cb eac0d83a fb8d0cf7
  52. cbb8324f 0d7882e5 d0762fc5 b7210eaf c2e9adac 32ab7aac
  53. 49693dfb f83724c2 ec0736ee 31c80291""")
  54. q = _sws("""c773218c 737ec8ee 993b4f2d ed30f48e dace915f""")
  55. x = _sws("""2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614""")
  56. k = _sws("""358dad57 1462710f 50e254cf 1a376b2b deaadfbf""")
  57. k_inverse = _sws("""0d516729 8202e49b 4116ac10 4fc3f415 ae52f917""")
  58. m = b2a_hex(b("abc"))
  59. m_hash = _sws("""a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d""")
  60. r = _sws("""8bac1ab6 6410435c b7181f95 b16ab97c 92b341c0""")
  61. s = _sws("""41e2345f 1f56df24 58f426d1 55b4ba2d b6dcd8c8""")
  62. def setUp(self):
  63. global DSA, Random, bytes_to_long, size
  64. from Crypto.PublicKey import DSA
  65. from Crypto import Random
  66. from Crypto.Util.number import bytes_to_long, inverse, size
  67. self.dsa = DSA
  68. def test_generate_1arg(self):
  69. """DSA (default implementation) generated key (1 argument)"""
  70. dsaObj = self.dsa.generate(1024)
  71. self._check_private_key(dsaObj)
  72. pub = dsaObj.publickey()
  73. self._check_public_key(pub)
  74. def test_generate_2arg(self):
  75. """DSA (default implementation) generated key (2 arguments)"""
  76. dsaObj = self.dsa.generate(1024, Random.new().read)
  77. self._check_private_key(dsaObj)
  78. pub = dsaObj.publickey()
  79. self._check_public_key(pub)
  80. def test_construct_4tuple(self):
  81. """DSA (default implementation) constructed key (4-tuple)"""
  82. (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
  83. dsaObj = self.dsa.construct((y, g, p, q))
  84. self._test_verification(dsaObj)
  85. def test_construct_5tuple(self):
  86. """DSA (default implementation) constructed key (5-tuple)"""
  87. (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
  88. dsaObj = self.dsa.construct((y, g, p, q, x))
  89. self._test_signing(dsaObj)
  90. self._test_verification(dsaObj)
  91. def _check_private_key(self, dsaObj):
  92. # Check capabilities
  93. self.assertEqual(1, dsaObj.has_private())
  94. self.assertEqual(1, dsaObj.can_sign())
  95. self.assertEqual(0, dsaObj.can_encrypt())
  96. self.assertEqual(0, dsaObj.can_blind())
  97. # Check dsaObj.[ygpqx] -> dsaObj.key.[ygpqx] mapping
  98. self.assertEqual(dsaObj.y, dsaObj.key.y)
  99. self.assertEqual(dsaObj.g, dsaObj.key.g)
  100. self.assertEqual(dsaObj.p, dsaObj.key.p)
  101. self.assertEqual(dsaObj.q, dsaObj.key.q)
  102. self.assertEqual(dsaObj.x, dsaObj.key.x)
  103. # Sanity check key data
  104. self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
  105. self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
  106. self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
  107. self.assertEqual(dsaObj.y, pow(dsaObj.g, dsaObj.x, dsaObj.p)) # y == g**x mod p
  108. self.assertEqual(1, 0 < dsaObj.x < dsaObj.q) # 0 < x < q
  109. def _check_public_key(self, dsaObj):
  110. k = a2b_hex(self.k)
  111. m_hash = a2b_hex(self.m_hash)
  112. # Check capabilities
  113. self.assertEqual(0, dsaObj.has_private())
  114. self.assertEqual(1, dsaObj.can_sign())
  115. self.assertEqual(0, dsaObj.can_encrypt())
  116. self.assertEqual(0, dsaObj.can_blind())
  117. # Check dsaObj.[ygpq] -> dsaObj.key.[ygpq] mapping
  118. self.assertEqual(dsaObj.y, dsaObj.key.y)
  119. self.assertEqual(dsaObj.g, dsaObj.key.g)
  120. self.assertEqual(dsaObj.p, dsaObj.key.p)
  121. self.assertEqual(dsaObj.q, dsaObj.key.q)
  122. # Check that private parameters are all missing
  123. self.assertEqual(0, hasattr(dsaObj, 'x'))
  124. self.assertEqual(0, hasattr(dsaObj.key, 'x'))
  125. # Sanity check key data
  126. self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
  127. self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
  128. self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
  129. # Public-only key objects should raise an error when .sign() is called
  130. self.assertRaises(TypeError, dsaObj.sign, m_hash, k)
  131. # Check __eq__ and __ne__
  132. self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_
  133. self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf
  134. def _test_signing(self, dsaObj):
  135. k = a2b_hex(self.k)
  136. m_hash = a2b_hex(self.m_hash)
  137. r = bytes_to_long(a2b_hex(self.r))
  138. s = bytes_to_long(a2b_hex(self.s))
  139. (r_out, s_out) = dsaObj.sign(m_hash, k)
  140. self.assertEqual((r, s), (r_out, s_out))
  141. def _test_verification(self, dsaObj):
  142. m_hash = a2b_hex(self.m_hash)
  143. r = bytes_to_long(a2b_hex(self.r))
  144. s = bytes_to_long(a2b_hex(self.s))
  145. self.assertEqual(1, dsaObj.verify(m_hash, (r, s)))
  146. self.assertEqual(0, dsaObj.verify(m_hash + b("\0"), (r, s)))
  147. class DSAFastMathTest(DSATest):
  148. def setUp(self):
  149. DSATest.setUp(self)
  150. self.dsa = DSA.DSAImplementation(use_fast_math=True)
  151. def test_generate_1arg(self):
  152. """DSA (_fastmath implementation) generated key (1 argument)"""
  153. DSATest.test_generate_1arg(self)
  154. def test_generate_2arg(self):
  155. """DSA (_fastmath implementation) generated key (2 arguments)"""
  156. DSATest.test_generate_2arg(self)
  157. def test_construct_4tuple(self):
  158. """DSA (_fastmath implementation) constructed key (4-tuple)"""
  159. DSATest.test_construct_4tuple(self)
  160. def test_construct_5tuple(self):
  161. """DSA (_fastmath implementation) constructed key (5-tuple)"""
  162. DSATest.test_construct_5tuple(self)
  163. class DSASlowMathTest(DSATest):
  164. def setUp(self):
  165. DSATest.setUp(self)
  166. self.dsa = DSA.DSAImplementation(use_fast_math=False)
  167. def test_generate_1arg(self):
  168. """DSA (_slowmath implementation) generated key (1 argument)"""
  169. DSATest.test_generate_1arg(self)
  170. def test_generate_2arg(self):
  171. """DSA (_slowmath implementation) generated key (2 arguments)"""
  172. DSATest.test_generate_2arg(self)
  173. def test_construct_4tuple(self):
  174. """DSA (_slowmath implementation) constructed key (4-tuple)"""
  175. DSATest.test_construct_4tuple(self)
  176. def test_construct_5tuple(self):
  177. """DSA (_slowmath implementation) constructed key (5-tuple)"""
  178. DSATest.test_construct_5tuple(self)
  179. def get_tests(config={}):
  180. tests = []
  181. tests += list_test_cases(DSATest)
  182. try:
  183. from Crypto.PublicKey import _fastmath
  184. tests += list_test_cases(DSAFastMathTest)
  185. except ImportError:
  186. from distutils.sysconfig import get_config_var
  187. import inspect
  188. _fm_path = os.path.normpath(os.path.dirname(os.path.abspath(
  189. inspect.getfile(inspect.currentframe())))
  190. +"/../../PublicKey/_fastmath"+get_config_var("SO"))
  191. if os.path.exists(_fm_path):
  192. raise ImportError("While the _fastmath module exists, importing "+
  193. "it failed. This may point to the gmp or mpir shared library "+
  194. "not being in the path. _fastmath was found at "+_fm_path)
  195. tests += list_test_cases(DSASlowMathTest)
  196. return tests
  197. if __name__ == '__main__':
  198. suite = lambda: unittest.TestSuite(get_tests())
  199. unittest.main(defaultTest='suite')
  200. # vim:set ts=4 sw=4 sts=4 expandtab: