1
  
2
  
3
  
4
  
5
  
6
  
7
  
8
  
9
  
10
  
11
  
12
  
13
  
14
  
15
  
16
  
17
  
18
  
19
  
20
  
21
  
22
  
23
  
24
  
25
  
26
  
27
  
28
  
29
  
30
  
31
  
32
  
33
  
34
  
35
  
36
  
37
  
38
  
39
  
40
  
41
  
42
  
43
  
44
  
45
  
46
  
47
  
48
  
49
  
50
  
51
  
52
  
53
  
54
  
55
  
56
  
57
  
58
  
59
  
60
  
61
  
62
  
63
  
64
  
65
  
66
  
67
  
68
  
69
  
70
  
71
  
72
  
73
  
74
  
75
  
76
  
77
  
78
  
79
  
80
  
81
  
82
  
83
  
84
  
85
  
86
  
87
  
88
  
89
  
90
  
91
  
92
  
93
  
94
  
95
  
96
  
97
  
98
  
99
  
100
  
101
  
102
  
103
  
104
  
105
  
106
  
107
  
108
  
109
  
110
  
111
  
112
  
113
  
114
  
115
  
116
  
117
  
118
  
119
  
120
  
121
  
122
  
123
  
124
  
125
  
126
  
127
  
128
  
129
  
130
  
131
  
132
  
133
  
134
  
135
  
136
  
137
  
138
  
139
  
140
  
141
  
142
  
143
  
144
  
145
  
146
  
147
  
148
  
149
  
150
  
151
  
152
  
153
  
154
  
155
  
156
  
157
  
158
  
159
  
160
  
161
  
162
  
163
  
164
  
165
  
166
  
167
  
168
  
169
  
170
  
171
  
172
  
173
  
174
  
175
  
176
  
177
  
178
  
179
  
180
  
181
  
182
  
183
  
184
  
185
  
186
  
187
  
188
  
189
  
190
  
191
  
192
  
193
  
194
  
195
  
196
  
197
  
198
  
199
  
200
  
201
  
202
  
203
  
204
  
205
  
206
  
207
  
208
  
209
  
210
  
211
  
212
  
213
  
214
  
215
  
216
  
217
  
218
  
219
  
220
  
221
  
222
  
223
  
224
  
225
  
226
  
227
  
228
  
229
  
230
  
231
  
232
  
233
  
234
  
235
  
236
  
237
  
238
  
239
  
240
  
241
  
242
  
243
  
244
  
245
  
246
  
247
  
248
  
249
  
250
  
251
  
252
  
253
  
254
  
255
  
256
  
257
  
258
  
259
  
260
  
261
  
262
  
263
  
264
  
265
  
266
  
267
  
268
  
269
  
270
  
271
  
272
  
273
  
274
  
275
  
276
  
277
  
278
  
279
  
280
  
281
  
282
  
283
  
284
  
285
  
286
  
287
  
288
  
289
  
290
  
291
  
292
  
293
  
294
  
295
  
296
  
297
  
298
  
299
  
300
  
301
  
302
  
303
  
304
  
305
  
306
  
307
  
308
  
309
  
310
  
311
  
312
  
313
  
314
  
315
  
316
  
317
  
318
  
319
  
320
  
321
  
322
  
323
  
324
  
325
  
326
  
327
  
328
  
329
  
330
  
331
  
332
  
333
  
334
  
335
  
336
  
337
  
338
  
339
  
340
  
341
  
342
  
343
  
344
  
345
  
346
  
347
  
348
  
349
  
350
  
351
  
352
  
353
  
354
  
355
  
356
  
357
  
358
  
359
  
360
  
361
  
362
  
363
  
364
  
365
  
366
  
367
  
368
  
369
  
370
  
371
  
372
  
373
  
374
  
375
  
376
  
377
  
378
  
379
  
380
  
381
  
382
  
383
  
384
  
385
  
386
  
387
  
388
  
389
  
390
  
391
  
392
  
393
  
394
  
395
  
396
  
397
  
398
  
399
  
400
  
401
  
402
  
403
  
404
  
405
  
406
  
407
  
408
  
409
  
410
  
411
  
412
  
413
  
414
  
415
  
416
  
417
  
418
  
419
  
420
  
421
  
422
  
423
  
424
  
425
  
 
//! The Digital Signature Algorithm DSA is part of the NIST Digital 
//! Signature Standard DSS, FIPS-186 (1993). 
 
#pike __REAL_VERSION__ 
#pragma strict_types 
#require constant(Crypto.Hash) 
 
inherit Crypto.Sign; 
 
//! Returns the string @expr{"DSA"@}. 
string(8bit) name() { return "DSA"; } 
 
class State { 
  inherit ::this_program; 
 
  protected string _sprintf(int t) 
  { 
    return t=='O' && sprintf("%O(%d,%d)", this_program, p->size(), q->size()); 
  } 
 
  // 
  // --- Variables and accessors 
  // 
 
  protected Gmp.mpz|zero p; // Modulo 
  protected Gmp.mpz|zero q; // Group order 
  protected Gmp.mpz|zero g; // Generator 
 
  protected Gmp.mpz|zero y; // Public key 
  protected Gmp.mpz|zero x; // Private key 
 
  protected function(int(0..):string(8bit)) random = random_string; 
 
  Gmp.mpz|zero get_p() { return p; } //! Returns the DSA modulo (p). 
  Gmp.mpz|zero get_q() { return q; } //! Returns the DSA group order (q). 
  Gmp.mpz|zero get_g() { return g; } //! Returns the DSA generator (g). 
  Gmp.mpz|zero get_y() { return y; } //! Returns the DSA public key (y). 
  Gmp.mpz|zero get_x() { return x; } //! Returns the DSA private key (x). 
 
  //! Sets the random function, used to generate keys and parameters, to 
  //! the function @[r]. Default is @[random_string]. 
  this_program set_random(function(int(0..):string(8bit)) r) 
  { 
    random = r; 
    return this; 
  } 
 
  //! Returns the string @expr{"DSA"@}. 
  string(8bit) name() { return "DSA"; } 
 
  // 
  // --- Key methods 
  // 
 
  //! Sets the public key in this DSA object. 
  //! @param modulo 
  //!   This is the p parameter. 
  //! @param order 
  //!   This is the group order q parameter. 
  //! @param generator 
  //!   This is the g parameter. 
  //! @param kye 
  //!   This is the public key y parameter. 
  this_program set_public_key(Gmp.mpz modulo, Gmp.mpz order, 
                              Gmp.mpz generator, Gmp.mpz key) 
  { 
    p = modulo; 
    q = order; 
    g = generator; 
    y = key; 
    return this; 
  } 
 
  //! Sets the public key in this DSA object. 
  //! 
  //! @param params 
  //!   The finite-field diffie-hellman group parameters. 
  //! @param key 
  //!   The public key y parameter. 
  variant this_program set_public_key(.DH.Parameters params, 
                                      Gmp.mpz key) 
  { 
    p = params->p; 
    q = params->q; 
    g = params->g; 
    y = key; 
    return this; 
  } 
 
  //! Compares the public key in this object with that in the provided 
  //! DSA object. 
  int(0..1) public_key_equal(this_program dsa) 
  { 
    return (p == dsa->get_p()) && (q == dsa->get_q()) && 
      (g == dsa->get_g()) && (y == dsa->get_y()); 
  } 
 
  //! Compares the keys of this DSA object with something other. 
  protected int(0..1) _equal(mixed other) 
  { 
    if (!objectp(other) || (object_program(other) != object_program(this)) || 
        !public_key_equal([object(this_program)]other)) { 
      return 0; 
    } 
    this_program dsa = [object(this_program)]other; 
    return x == dsa->get_x(); 
  } 
 
  //! Sets the private key, the x parameter, in this DSA object. 
  this_program set_private_key(Gmp.mpz secret) 
  { 
    x = secret; 
    return this; 
  } 
 
  // 
  // --- Key generation 
  // 
 
#if !constant(Nettle.dsa_generate_keypair) 
 
#define SEED_LENGTH 20 
  protected string(8bit) nist_hash(Gmp.mpz x) 
  { 
    string(8bit) s = x->digits(256); 
    return .SHA1.hash(s[sizeof(s) - SEED_LENGTH..]); 
  } 
 
  // The (slow) NIST method of generating a DSA prime pair. Algorithm 
  // 4.56 of Handbook of Applied Cryptography. 
  protected array(Gmp.mpz) nist_primes(int l) 
  { 
    if ( (l < 0) || (l > 8) ) 
      error( "Unsupported key size.\n" ); 
 
    int L = 512 + 64 * l; 
 
    int n = (L-1) / 160; 
    //  int b = (L-1) % 160; 
 
    for (;;) 
    { 
      /* Generate q */ 
      string(8bit) seed = random(SEED_LENGTH); 
      Gmp.mpz s = Gmp.mpz(seed, 256); 
 
      string(8bit) h = [string(8bit)] 
        (nist_hash(s) ^ nist_hash( [object(Gmp.mpz)](s + 1) )); 
 
      h = sprintf("%c%s%c", 
                  [int(8bit)](h[0] | 0x80), 
                  h[1..<1], 
                  [int(8bit)](h[-1] | 1)); 
 
      Gmp.mpz q = Gmp.mpz(h, 256); 
 
      if (!q->probably_prime_p()) 
        continue; 
 
      /* q is a prime, with overwelming probability. */ 
 
      int i, j; 
 
      for (i = 0, j = 2; i < 4096; i++, j += n+1) 
      { 
        string(8bit) buffer = ""; 
        int k; 
 
        for (k = 0; k<= n; k++) 
          buffer = nist_hash( [object(Gmp.mpz)](s + j + k) ) + buffer; 
 
        buffer = buffer[sizeof(buffer) - L/8 ..]; 
        buffer[0] = [int(8bit)](buffer[0] | 0x80); 
 
        Gmp.mpz p = Gmp.mpz(buffer, 256); 
 
        p -= p % (2 * q) - 1; 
 
        if (p->probably_prime_p()) 
        { 
          /* Done */ 
          return ({ p, q }); 
        } 
      } 
    } 
  } 
 
  protected Gmp.mpz find_generator(Gmp.mpz p, Gmp.mpz q) 
  { 
    Gmp.mpz e = [object(Gmp.mpz)]((p - 1) / q); 
    Gmp.mpz g; 
 
    do { 
      /* A random number in { 2, 3, ... p - 2 } */ 
      g = ([object(Gmp.mpz)](random_number( [object(Gmp.mpz)](p-3) ) + 2)) 
        /* Exponentiate to get an element of order 1 or q */ 
        ->powm(e, p); 
    } while (g == 1); 
 
    return g; 
  } 
 
  // Generate key parameters (p, q and g) using the NIST DSA prime pair 
  // generation algorithm. @[bits] must be multiple of 64. 
  protected void generate_parameters(int bits) 
  { 
    if (!bits || bits % 64) 
      error( "Unsupported key size.\n" ); 
 
    [p, q] = nist_primes(bits / 64 - 8); 
 
    if (p % q != 1) 
      error( "Internal error.\n" ); 
 
    if (q->size() != 160) 
      error( "Internal error.\n" ); 
 
    g = find_generator(p, q); 
 
    if ( (g == 1) || (g->powm(q, p) != 1)) 
      error( "Internal error.\n" ); 
  } 
 
  variant this_program generate_key(int p_bits, int q_bits) 
  { 
    if(q_bits!=160) 
      error("Only 1024/160 supported with Nettle version < 2.0\n"); 
    generate_parameters(1024); 
    return generate_key(); 
  } 
 
#else // !constant(Nettle.dsa_generate_keypair) 
 
  //! Generates DSA parameters (p, q, g) and key (x, y). Depending on 
  //! Nettle version @[q_bits] can be 160, 224 and 256 bits. 160 works 
  //! for all versions. 
  variant this_program generate_key(int p_bits, int q_bits) 
  { 
    [ p, q, g, y, x ] = Nettle.dsa_generate_keypair(p_bits, q_bits, random); 
    return this; 
  } 
 
#endif 
 
  //! Generates a public/private key pair with the specified 
  //! finite field diffie-hellman parameters. 
  variant this_program generate_key(.DH.Parameters params) 
  { 
    p = params->p; 
    g = params->g; 
    q = params->q; 
 
    [y, x] = params->generate_keypair(random); 
    return this; 
  } 
 
  //! Generates a public/private key pair. Needs the public parameters 
  //! p, q and g set, through one of @[set_public_key], 
  //! @[generate_key(int,int)] or @[generate_key(params)]. 
  variant this_program generate_key() 
  { 
    /* x in { 2, 3, ... q - 1 } */ 
    if(!p || !q || !g) error("Public parameters not set..\n"); 
    x = [object(Gmp.mpz)](random_number( [object(Gmp.mpz)](q-2) ) + 2); 
    y = g->powm(x, p); 
 
    return this; 
  } 
 
 
  // 
  // --- PKCS methods 
  // 
 
#define Sequence Standards.ASN1.Types.Sequence 
#define Integer Standards.ASN1.Types.Integer 
#define BitString Standards.ASN1.Types.BitString 
 
  //! Returns the AlgorithmIdentifier as defined in 
  //! @rfc{5280:4.1.1.2@} including the DSA parameters. 
  Sequence pkcs_algorithm_identifier() 
  { 
    return 
      Sequence( ({ Standards.PKCS.Identifiers.dsa_id, 
                   Sequence( ({ Integer(get_p()), 
                                Integer(get_q()), 
                                Integer(get_g()) 
                             }) ) 
                }) ); 
  } 
 
 
  //! Returns the PKCS-1 algorithm identifier for DSA and the provided 
  //! hash algorithm. Only @[SHA1] supported. 
  object(Sequence)|zero pkcs_signature_algorithm_id(.Hash hash) 
  { 
    switch(hash->name()) 
    { 
    case "sha1": 
      return Sequence( ({ Standards.PKCS.Identifiers.dsa_sha_id }) ); 
      break; 
    case "sha224": 
      return Sequence( ({ Standards.PKCS.Identifiers.dsa_sha224_id }) ); 
      break; 
    case "sha256": 
      return Sequence( ({ Standards.PKCS.Identifiers.dsa_sha256_id }) ); 
      break; 
    } 
    return 0; 
  } 
 
  //! Creates a SubjectPublicKeyInfo ASN.1 sequence for the object. 
  //! See @rfc{5280:4.1.2.7@}. 
  Sequence pkcs_public_key() 
  { 
    return Sequence(({ 
                      pkcs_algorithm_identifier(), 
                      BitString(Integer(get_y())->get_der()), 
                    })); 
  } 
 
#undef BitString 
#undef Integer 
#undef Sequence 
 
  //! Signs the @[message] with a PKCS-1 signature using hash algorithm 
  //! @[h]. 
  string(8bit) pkcs_sign(string(8bit) message, .Hash h) 
  { 
    array sign = map(raw_sign(hash(message, h)), Standards.ASN1.Types.Integer); 
    return Standards.ASN1.Types.Sequence(sign)->get_der(); 
  } 
 
  // FIXME: Consider implementing RFC 6979. 
 
#define Object Standards.ASN1.Types.Object 
 
  //! Verify PKCS-1 signature @[sign] of message @[message] using hash 
  //! algorithm @[h]. 
  int(0..1) pkcs_verify(string(8bit) message, .Hash h, string(8bit) sign) 
  { 
    object(Object)|zero a = Standards.ASN1.Decode.secure_der_decode(sign); 
 
    // The signature is the DER-encoded ASN.1 sequence Dss-Sig-Value 
    // with the two integers r and s. See RFC 3279 section 2.2.2. 
    if (!a 
        || (a->type_name != "SEQUENCE") 
        || (sizeof([array]a->elements) != 2) 
        || (sizeof( ([array(object(Object))]a->elements)->type_name - 
                    ({ "INTEGER" })))) 
      return 0; 
 
    return raw_verify(hash(message, h), 
                      [object(Gmp.mpz)]([array(object(Object))]a->elements)[0]-> 
                      value, 
                      [object(Gmp.mpz)]([array(object(Object))]a->elements)[1]-> 
                      value); 
  } 
 
#undef Object 
 
  // 
  //  --- Below are methods for DSA applied in other standards. 
  // 
 
  //! Makes a DSA hash of the message @[msg]. 
  Gmp.mpz hash(string(8bit) msg, .Hash h) 
  { 
    string(8bit) digest = h->hash(msg)[..q->size()/8-1]; 
    return [object(Gmp.mpz)](Gmp.mpz(digest, 256) % q); 
  } 
 
  protected Gmp.mpz random_number(Gmp.mpz n) 
  { 
    return [object(Gmp.mpz)](Gmp.mpz(random( [int(0..)](q->size() + 10 / 8)), 
                                     256) % n); 
  } 
 
  protected Gmp.mpz random_exponent() 
  { 
    return [object(Gmp.mpz)](random_number([object(Gmp.mpz)](q - 1)) + 1); 
  } 
 
  //! Sign the message @[h]. Returns the signature as two @[Gmp.mpz] 
  //! objects. 
  array(Gmp.mpz) raw_sign(Gmp.mpz h, void|Gmp.mpz k) 
  { 
    if(!k) k = random_exponent(); 
 
    Gmp.mpz r = [object(Gmp.mpz)](g->powm(k, p) % q); 
    Gmp.mpz s = [object(Gmp.mpz)]((k->invert(q) * (h + [object(Gmp.mpz)](x*r))) % q); 
 
    return ({ r, s }); 
  } 
 
  //! Verify the signature @[r],@[s] against the message @[h]. 
  int(0..1) raw_verify(Gmp.mpz h, Gmp.mpz r, Gmp.mpz s) 
  { 
    object(Gmp.mpz)|zero w; 
    if (catch 
      { 
        w = s->invert(q); 
      }) 
      /* Non-invertible */ 
      return 0; 
 
    /* The inner %q's are redundant, as g^q == y^q == 1 (mod p) */ 
    return r == (g->powm( [object(Gmp.mpz)](w * h % q), p) * 
                 y->powm( [object(Gmp.mpz)](w * r % q), p) % p) % q; 
  } 
 
  int(0..) key_size() 
  { 
    return p->size(); 
  } 
} 
 
//! Calling `() will return a @[State] object. 
protected State `()() 
{ 
  return State(); 
}