Debian Codegraph @

lib/Crypto/SelfTest/PublicKey/test_DSA.py

raw symbols SCIP
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 <[email protected]>
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
25 """Self-test suite for Crypto.PublicKey.DSA"""
26
27 import os
28 from Crypto.Util.py3compat import *
29
30 import unittest
31 from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
32
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
40 class DSATest(unittest.TestCase):
41 # Test vector from "Appendix 5. Example of the DSA" of
42 # "Digital Signature Standard (DSS)",
43 # U.S. Department of Commerce/National Institute of Standards and Technology
44 # FIPS 186-2 (+Change Notice), 2000 January 27.
45 # http://csrc.nist.gov/publications/fips/fips186-2/fips186-2-change1.pdf
46
47 y = _sws("""19131871 d75b1612 a819f29d 78d1b0d7 346f7aa7 7bb62a85
48 9bfd6c56 75da9d21 2d3a36ef 1672ef66 0b8c7c25 5cc0ec74
49 858fba33 f44c0669 9630a76b 030ee333""")
50
51 g = _sws("""626d0278 39ea0a13 413163a5 5b4cb500 299d5522 956cefcb
52 3bff10f3 99ce2c2e 71cb9de5 fa24babf 58e5b795 21925c9c
53 c42e9f6f 464b088c c572af53 e6d78802""")
54
55 p = _sws("""8df2a494 492276aa 3d25759b b06869cb eac0d83a fb8d0cf7
56 cbb8324f 0d7882e5 d0762fc5 b7210eaf c2e9adac 32ab7aac
57 49693dfb f83724c2 ec0736ee 31c80291""")
58
59 q = _sws("""c773218c 737ec8ee 993b4f2d ed30f48e dace915f""")
60
61 x = _sws("""2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614""")
62
63 k = _sws("""358dad57 1462710f 50e254cf 1a376b2b deaadfbf""")
64 k_inverse = _sws("""0d516729 8202e49b 4116ac10 4fc3f415 ae52f917""")
65 m = b2a_hex(b("abc"))
66 m_hash = _sws("""a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d""")
67 r = _sws("""8bac1ab6 6410435c b7181f95 b16ab97c 92b341c0""")
68 s = _sws("""41e2345f 1f56df24 58f426d1 55b4ba2d b6dcd8c8""")
69
70 def setUp(self):
71 global DSA, Random, bytes_to_long, size
72 from Crypto.PublicKey import DSA
73 from Crypto import Random
74 from Crypto.Util.number import bytes_to_long, inverse, size
75
76 self.dsa = DSA
77
78 def test_generate_1arg(self):
79 """DSA (default implementation) generated key (1 argument)"""
80 dsaObj = self.dsa.generate(1024)
81 self._check_private_key(dsaObj)
82 pub = dsaObj.public_key()
83 self._check_public_key(pub)
84
85 def test_generate_2arg(self):
86 """DSA (default implementation) generated key (2 arguments)"""
87 dsaObj = self.dsa.generate(1024, Random.new().read)
88 self._check_private_key(dsaObj)
89 pub = dsaObj.public_key()
90 self._check_public_key(pub)
91
92 def test_construct_4tuple(self):
93 """DSA (default implementation) constructed key (4-tuple)"""
94 (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
95 dsaObj = self.dsa.construct((y, g, p, q))
96 self._test_verification(dsaObj)
97
98 def test_construct_5tuple(self):
99 """DSA (default implementation) constructed key (5-tuple)"""
100 (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
101 dsaObj = self.dsa.construct((y, g, p, q, x))
102 self._test_signing(dsaObj)
103 self._test_verification(dsaObj)
104
105 def test_construct_bad_key4(self):
106 (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
107 tup = (y, g, p+1, q)
108 self.assertRaises(ValueError, self.dsa.construct, tup)
109
110 tup = (y, g, p, q+1)
111 self.assertRaises(ValueError, self.dsa.construct, tup)
112
113 tup = (y, 1, p, q)
114 self.assertRaises(ValueError, self.dsa.construct, tup)
115
116 def test_construct_bad_key5(self):
117 (y, g, p, q, x) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q, self.x)]
118 tup = (y, g, p, q, x+1)
119 self.assertRaises(ValueError, self.dsa.construct, tup)
120
121 tup = (y, g, p, q, q+10)
122 self.assertRaises(ValueError, self.dsa.construct, tup)
123
124 def _check_private_key(self, dsaObj):
125 # Check capabilities
126 self.assertEqual(1, dsaObj.has_private())
127 self.assertEqual(1, dsaObj.can_sign())
128 self.assertEqual(0, dsaObj.can_encrypt())
129
130 # Sanity check key data
131 self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
132 self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
133 self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
134 self.assertEqual(dsaObj.y, pow(dsaObj.g, dsaObj.x, dsaObj.p)) # y == g**x mod p
135 self.assertEqual(1, 0 < dsaObj.x < dsaObj.q) # 0 < x < q
136
137 def _check_public_key(self, dsaObj):
138 k = bytes_to_long(a2b_hex(self.k))
139 m_hash = bytes_to_long(a2b_hex(self.m_hash))
140
141 # Check capabilities
142 self.assertEqual(0, dsaObj.has_private())
143 self.assertEqual(1, dsaObj.can_sign())
144 self.assertEqual(0, dsaObj.can_encrypt())
145
146 # Check that private parameters are all missing
147 self.assertEqual(0, hasattr(dsaObj, 'x'))
148
149 # Sanity check key data
150 self.assertEqual(1, dsaObj.p > dsaObj.q) # p > q
151 self.assertEqual(160, size(dsaObj.q)) # size(q) == 160 bits
152 self.assertEqual(0, (dsaObj.p - 1) % dsaObj.q) # q is a divisor of p-1
153
154 # Public-only key objects should raise an error when .sign() is called
155 self.assertRaises(TypeError, dsaObj._sign, m_hash, k)
156
157 # Check __eq__ and __ne__
158 self.assertEqual(dsaObj.public_key() == dsaObj.public_key(),True) # assert_
159 self.assertEqual(dsaObj.public_key() != dsaObj.public_key(),False) # assertFalse
160
161 self.assertEqual(dsaObj.public_key(), dsaObj.publickey())
162
163 def _test_signing(self, dsaObj):
164 k = bytes_to_long(a2b_hex(self.k))
165 m_hash = bytes_to_long(a2b_hex(self.m_hash))
166 r = bytes_to_long(a2b_hex(self.r))
167 s = bytes_to_long(a2b_hex(self.s))
168 (r_out, s_out) = dsaObj._sign(m_hash, k)
169 self.assertEqual((r, s), (r_out, s_out))
170
171 def _test_verification(self, dsaObj):
172 m_hash = bytes_to_long(a2b_hex(self.m_hash))
173 r = bytes_to_long(a2b_hex(self.r))
174 s = bytes_to_long(a2b_hex(self.s))
175 self.assertTrue(dsaObj._verify(m_hash, (r, s)))
176 self.assertFalse(dsaObj._verify(m_hash + 1, (r, s)))
177
178 def test_repr(self):
179 (y, g, p, q) = [bytes_to_long(a2b_hex(param)) for param in (self.y, self.g, self.p, self.q)]
180 dsaObj = self.dsa.construct((y, g, p, q))
181 repr(dsaObj)
182
183
184 class DSADomainTest(unittest.TestCase):
185
186 def test_domain1(self):
187 """Verify we can generate new keys in a given domain"""
188 dsa_key_1 = DSA.generate(1024)
189 domain_params = dsa_key_1.domain()
190
191 dsa_key_2 = DSA.generate(1024, domain=domain_params)
192 self.assertEqual(dsa_key_1.p, dsa_key_2.p)
193 self.assertEqual(dsa_key_1.q, dsa_key_2.q)
194 self.assertEqual(dsa_key_1.g, dsa_key_2.g)
195
196 self.assertEqual(dsa_key_1.domain(), dsa_key_2.domain())
197
198 def _get_weak_domain(self):
199
200 from Crypto.Math.Numbers import Integer
201 from Crypto.Math import Primality
202
203 p = Integer(4)
204 while p.size_in_bits() != 1024 or Primality.test_probable_prime(p) != Primality.PROBABLY_PRIME:
205 q1 = Integer.random(exact_bits=80)
206 q2 = Integer.random(exact_bits=80)
207 q = q1 * q2
208 z = Integer.random(exact_bits=1024-160)
209 p = z * q + 1
210
211 h = Integer(2)
212 g = 1
213 while g == 1:
214 g = pow(h, z, p)
215 h += 1
216
217 return (p, q, g)
218
219
220 def test_generate_error_weak_domain(self):
221 """Verify that domain parameters with composite q are rejected"""
222
223 domain_params = self._get_weak_domain()
224 self.assertRaises(ValueError, DSA.generate, 1024, domain=domain_params)
225
226
227 def test_construct_error_weak_domain(self):
228 """Verify that domain parameters with composite q are rejected"""
229
230 from Crypto.Math.Numbers import Integer
231
232 p, q, g = self._get_weak_domain()
233 y = pow(g, 89, p)
234 self.assertRaises(ValueError, DSA.construct, (y, g, p, q))
235
236
237 def get_tests(config={}):
238 tests = []
239 tests += list_test_cases(DSATest)
240 tests += list_test_cases(DSADomainTest)
241 return tests
242
243 if __name__ == '__main__':
244 suite = lambda: unittest.TestSuite(get_tests())
245 unittest.main(defaultTest='suite')
246
247 # vim:set ts=4 sw=4 sts=4 expandtab: