Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(55)

Side by Side Diff: mozilla/security/nss/lib/freebl/pqg.c

Issue 14249009: Change the NSS and NSPR source tree to the new directory structure to be (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/deps/third_party/nss/
Patch Set: Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « mozilla/security/nss/lib/freebl/pqg.h ('k') | mozilla/security/nss/lib/freebl/rawhash.c » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /*
6 * PQG parameter generation/verification. Based on FIPS 186-3.
7 *
8 * $Id: pqg.c,v 1.26 2012/12/13 22:47:15 wtc%google.com Exp $
9 */
10 #ifdef FREEBL_NO_DEPEND
11 #include "stubs.h"
12 #endif
13
14 #include "prerr.h"
15 #include "secerr.h"
16
17 #include "prtypes.h"
18 #include "blapi.h"
19 #include "secitem.h"
20 #include "mpi.h"
21 #include "mpprime.h"
22 #include "mplogic.h"
23 #include "secmpi.h"
24
25 #define MAX_ITERATIONS 1000 /* Maximum number of iterations of primegen */
26
27 typedef enum {
28 FIPS186_1_TYPE, /* Probablistic */
29 FIPS186_3_TYPE, /* Probablistic */
30 FIPS186_3_ST_TYPE /* Shawe-Taylor provable */
31 } pqgGenType;
32
33 /*
34 * These test iterations are quite a bit larger than we previously had.
35 * This is because FIPS 186-3 is worried about the primes in PQG generation.
36 * It may be possible to purposefully construct composites which more
37 * iterations of Miller-Rabin than the for your normal randomly selected
38 * numbers.There are 3 ways to counter this: 1) use one of the cool provably
39 * prime algorithms (which would require a lot more work than DSA-2 deservers.
40 * 2) add a Lucas primality test (which requires coding a Lucas primality test,
41 * or 3) use a larger M-R test count. I chose the latter. It increases the time
42 * that it takes to prove the selected prime, but it shouldn't increase the
43 * overall time to run the algorithm (non-primes should still faile M-R
44 * realively quickly). If you want to get that last bit of performance,
45 * implement Lucas and adjust these two functions. See FIPS 186-3 Appendix C
46 * and F for more information.
47 */
48 int prime_testcount_p(int L, int N)
49 {
50 switch (L) {
51 case 1024:
52 return 40;
53 case 2048:
54 return 56;
55 case 3072:
56 return 64;
57 default:
58 break;
59 }
60 return 50; /* L = 512-960 */
61 }
62
63 /* The q numbers are different if you run M-R followd by Lucas. I created
64 * a separate function so if someone wanted to add the Lucas check, they
65 * could do so fairly easily */
66 int prime_testcount_q(int L, int N)
67 {
68 return prime_testcount_p(L,N);
69 }
70
71 /*
72 * generic function to make sure our input matches DSA2 requirements
73 * this gives us one place to go if we need to bump the requirements in the
74 * future.
75 */
76 static SECStatus
77 pqg_validate_dsa2(unsigned int L, unsigned int N)
78 {
79
80 switch (L) {
81 case 1024:
82 if (N != DSA1_Q_BITS) {
83 PORT_SetError(SEC_ERROR_INVALID_ARGS);
84 return SECFailure;
85 }
86 break;
87 case 2048:
88 if ((N != 224) && (N != 256)) {
89 PORT_SetError(SEC_ERROR_INVALID_ARGS);
90 return SECFailure;
91 }
92 break;
93 case 3072:
94 if (N != 256) {
95 PORT_SetError(SEC_ERROR_INVALID_ARGS);
96 return SECFailure;
97 }
98 break;
99 default:
100 PORT_SetError(SEC_ERROR_INVALID_ARGS);
101 return SECFailure;
102 }
103 return SECSuccess;
104 }
105
106 static unsigned int
107 pqg_get_default_N(unsigned int L)
108 {
109 unsigned int N = 0;
110 switch (L) {
111 case 1024:
112 N = DSA1_Q_BITS;
113 break;
114 case 2048:
115 N = 224;
116 break;
117 case 3072:
118 N = 256;
119 break;
120 default:
121 PORT_SetError(SEC_ERROR_INVALID_ARGS);
122 break; /* N already set to zero */
123 }
124 return N;
125 }
126
127 /*
128 * Select the lowest hash algorithm usable
129 */
130 static HASH_HashType
131 getFirstHash(unsigned int L, unsigned int N)
132 {
133 if (N < 224) {
134 return HASH_AlgSHA1;
135 }
136 if (N < 256) {
137 return HASH_AlgSHA224;
138 }
139 if (N < 384) {
140 return HASH_AlgSHA256;
141 }
142 if (N < 512) {
143 return HASH_AlgSHA384;
144 }
145 return HASH_AlgSHA512;
146 }
147
148 /*
149 * find the next usable hash algorthim
150 */
151 static HASH_HashType
152 getNextHash(HASH_HashType hashtype)
153 {
154 switch (hashtype) {
155 case HASH_AlgSHA1:
156 hashtype = HASH_AlgSHA224;
157 break;
158 case HASH_AlgSHA224:
159 hashtype = HASH_AlgSHA256;
160 break;
161 case HASH_AlgSHA256:
162 hashtype = HASH_AlgSHA384;
163 break;
164 case HASH_AlgSHA384:
165 hashtype = HASH_AlgSHA512;
166 break;
167 case HASH_AlgSHA512:
168 default:
169 hashtype = HASH_AlgTOTAL;
170 break;
171 }
172 return hashtype;
173 }
174
175 static unsigned int
176 HASH_ResultLen(HASH_HashType type)
177 {
178 const SECHashObject *hash_obj = HASH_GetRawHashObject(type);
179 if (hash_obj == NULL) {
180 return 0;
181 }
182 return hash_obj->length;
183 }
184
185 static SECStatus
186 HASH_HashBuf(HASH_HashType type, unsigned char *dest,
187 const unsigned char *src, PRUint32 src_len)
188 {
189 const SECHashObject *hash_obj = HASH_GetRawHashObject(type);
190 void *hashcx = NULL;
191 unsigned int dummy;
192
193 if (hash_obj == NULL) {
194 return SECFailure;
195 }
196
197 hashcx = hash_obj->create();
198 if (hashcx == NULL) {
199 return SECFailure;
200 }
201 hash_obj->begin(hashcx);
202 hash_obj->update(hashcx,src,src_len);
203 hash_obj->end(hashcx,dest, &dummy, hash_obj->length);
204 hash_obj->destroy(hashcx, PR_TRUE);
205 return SECSuccess;
206 }
207
208 unsigned int
209 PQG_GetLength(const SECItem *obj)
210 {
211 unsigned int len = obj->len;
212
213 if (obj->data == NULL) {
214 return 0;
215 }
216 if (len > 1 && obj->data[0] == 0) {
217 len--;
218 }
219 return len;
220 }
221
222 SECStatus
223 PQG_Check(const PQGParams *params)
224 {
225 unsigned int L,N;
226 SECStatus rv = SECSuccess;
227
228 if (params == NULL) {
229 PORT_SetError(SEC_ERROR_INVALID_ARGS);
230 return SECFailure;
231 }
232
233 L = PQG_GetLength(&params->prime)*BITS_PER_BYTE;
234 N = PQG_GetLength(&params->subPrime)*BITS_PER_BYTE;
235
236 if (L < 1024) {
237 int j;
238
239 /* handle DSA1 pqg parameters with less thatn 1024 bits*/
240 if ( N != DSA1_Q_BITS ) {
241 PORT_SetError(SEC_ERROR_INVALID_ARGS);
242 return SECFailure;
243 }
244 j = PQG_PBITS_TO_INDEX(L);
245 if ( j < 0 ) {
246 PORT_SetError(SEC_ERROR_INVALID_ARGS);
247 rv = SECFailure;
248 }
249 } else {
250 /* handle DSA2 parameters (includes DSA1, 1024 bits) */
251 rv = pqg_validate_dsa2(L, N);
252 }
253 return rv;
254 }
255
256 HASH_HashType
257 PQG_GetHashType(const PQGParams *params)
258 {
259 unsigned int L,N;
260
261 if (params == NULL) {
262 PORT_SetError(SEC_ERROR_INVALID_ARGS);
263 return HASH_AlgNULL;
264 }
265
266 L = PQG_GetLength(&params->prime)*BITS_PER_BYTE;
267 N = PQG_GetLength(&params->subPrime)*BITS_PER_BYTE;
268 return getFirstHash(L, N);
269 }
270
271 /* Get a seed for generating P and Q. If in testing mode, copy in the
272 ** seed from FIPS 186-1 appendix 5. Otherwise, obtain bytes from the
273 ** global random number generator.
274 */
275 static SECStatus
276 getPQseed(SECItem *seed, PRArenaPool* arena)
277 {
278 SECStatus rv;
279
280 if (!seed->data) {
281 seed->data = (unsigned char*)PORT_ArenaZAlloc(arena, seed->len);
282 }
283 if (!seed->data) {
284 PORT_SetError(SEC_ERROR_NO_MEMORY);
285 return SECFailure;
286 }
287 rv = RNG_GenerateGlobalRandomBytes(seed->data, seed->len);
288 /*
289 * NIST CMVP disallows a sequence of 20 bytes with the most
290 * significant byte equal to 0. Perhaps they interpret
291 * "a sequence of at least 160 bits" as "a number >= 2^159".
292 * So we always set the most significant bit to 1. (bug 334533)
293 */
294 seed->data[0] |= 0x80;
295 return rv;
296 }
297
298 /* Generate a candidate h value. If in testing mode, use the h value
299 ** specified in FIPS 186-1 appendix 5, h = 2. Otherwise, obtain bytes
300 ** from the global random number generator.
301 */
302 static SECStatus
303 generate_h_candidate(SECItem *hit, mp_int *H)
304 {
305 SECStatus rv = SECSuccess;
306 mp_err err = MP_OKAY;
307 #ifdef FIPS_186_1_A5_TEST
308 memset(hit->data, 0, hit->len);
309 hit->data[hit->len-1] = 0x02;
310 #else
311 rv = RNG_GenerateGlobalRandomBytes(hit->data, hit->len);
312 #endif
313 if (rv)
314 return SECFailure;
315 err = mp_read_unsigned_octets(H, hit->data, hit->len);
316 if (err) {
317 MP_TO_SEC_ERROR(err);
318 return SECFailure;
319 }
320 return SECSuccess;
321 }
322
323 static SECStatus
324 addToSeed(const SECItem * seed,
325 unsigned long addend,
326 int seedlen, /* g in 186-1 */
327 SECItem * seedout)
328 {
329 mp_int s, sum, modulus, tmp;
330 mp_err err = MP_OKAY;
331 SECStatus rv = SECSuccess;
332 MP_DIGITS(&s) = 0;
333 MP_DIGITS(&sum) = 0;
334 MP_DIGITS(&modulus) = 0;
335 MP_DIGITS(&tmp) = 0;
336 CHECK_MPI_OK( mp_init(&s) );
337 CHECK_MPI_OK( mp_init(&sum) );
338 CHECK_MPI_OK( mp_init(&modulus) );
339 SECITEM_TO_MPINT(*seed, &s); /* s = seed */
340 /* seed += addend */
341 if (addend < MP_DIGIT_MAX) {
342 CHECK_MPI_OK( mp_add_d(&s, (mp_digit)addend, &s) );
343 } else {
344 CHECK_MPI_OK( mp_init(&tmp) );
345 CHECK_MPI_OK( mp_set_ulong(&tmp, addend) );
346 CHECK_MPI_OK( mp_add(&s, &tmp, &s) );
347 }
348 /*sum = s mod 2**seedlen */
349 CHECK_MPI_OK( mp_div_2d(&s, (mp_digit)seedlen, NULL, &sum) );
350 if (seedout->data != NULL) {
351 SECITEM_ZfreeItem(seedout, PR_FALSE);
352 }
353 MPINT_TO_SECITEM(&sum, seedout, NULL);
354 cleanup:
355 mp_clear(&s);
356 mp_clear(&sum);
357 mp_clear(&modulus);
358 mp_clear(&tmp);
359 if (err) {
360 MP_TO_SEC_ERROR(err);
361 return SECFailure;
362 }
363 return rv;
364 }
365
366 /* Compute Hash[(SEED + addend) mod 2**g]
367 ** Result is placed in shaOutBuf.
368 ** This computation is used in steps 2 and 7 of FIPS 186 Appendix 2.2 and
369 ** step 11.2 of FIPS 186-3 Appendix A.1.1.2 .
370 */
371 static SECStatus
372 addToSeedThenHash(HASH_HashType hashtype,
373 const SECItem * seed,
374 unsigned long addend,
375 int seedlen, /* g in 186-1 */
376 unsigned char * hashOutBuf)
377 {
378 SECItem str = { 0, 0, 0 };
379 SECStatus rv;
380 rv = addToSeed(seed, addend, seedlen, &str);
381 if (rv != SECSuccess) {
382 return rv;
383 }
384 rv = HASH_HashBuf(hashtype, hashOutBuf, str.data, str.len);/* hash result */
385 if (str.data)
386 SECITEM_ZfreeItem(&str, PR_FALSE);
387 return rv;
388 }
389
390 /*
391 ** Perform steps 2 and 3 of FIPS 186-1, appendix 2.2.
392 ** Generate Q from seed.
393 */
394 static SECStatus
395 makeQfromSeed(
396 unsigned int g, /* input. Length of seed in bits. */
397 const SECItem * seed, /* input. */
398 mp_int * Q) /* output. */
399 {
400 unsigned char sha1[SHA1_LENGTH];
401 unsigned char sha2[SHA1_LENGTH];
402 unsigned char U[SHA1_LENGTH];
403 SECStatus rv = SECSuccess;
404 mp_err err = MP_OKAY;
405 int i;
406 /* ******************************************************************
407 ** Step 2.
408 ** "Compute U = SHA[SEED] XOR SHA[(SEED+1) mod 2**g]."
409 **/
410 CHECK_SEC_OK( SHA1_HashBuf(sha1, seed->data, seed->len) );
411 CHECK_SEC_OK( addToSeedThenHash(HASH_AlgSHA1, seed, 1, g, sha2) );
412 for (i=0; i<SHA1_LENGTH; ++i)
413 U[i] = sha1[i] ^ sha2[i];
414 /* ******************************************************************
415 ** Step 3.
416 ** "Form Q from U by setting the most signficant bit (the 2**159 bit)
417 ** and the least signficant bit to 1. In terms of boolean operations,
418 ** Q = U OR 2**159 OR 1. Note that 2**159 < Q < 2**160."
419 */
420 U[0] |= 0x80; /* U is MSB first */
421 U[SHA1_LENGTH-1] |= 0x01;
422 err = mp_read_unsigned_octets(Q, U, SHA1_LENGTH);
423 cleanup:
424 memset(U, 0, SHA1_LENGTH);
425 memset(sha1, 0, SHA1_LENGTH);
426 memset(sha2, 0, SHA1_LENGTH);
427 if (err) {
428 MP_TO_SEC_ERROR(err);
429 return SECFailure;
430 }
431 return rv;
432 }
433
434 /*
435 ** Perform steps 6 and 7 of FIPS 186-3, appendix A.1.1.2.
436 ** Generate Q from seed.
437 */
438 static SECStatus
439 makeQ2fromSeed(
440 HASH_HashType hashtype, /* selected Hashing algorithm */
441 unsigned int N, /* input. Length of q in bits. */
442 const SECItem * seed, /* input. */
443 mp_int * Q) /* output. */
444 {
445 unsigned char U[HASH_LENGTH_MAX];
446 SECStatus rv = SECSuccess;
447 mp_err err = MP_OKAY;
448 int N_bytes = N/BITS_PER_BYTE; /* length of N in bytes rather than bits */
449 int hashLen = HASH_ResultLen(hashtype);
450 int offset = 0;
451
452 /* ******************************************************************
453 ** Step 6.
454 ** "Compute U = hash[SEED] mod 2**N-1]."
455 **/
456 CHECK_SEC_OK( HASH_HashBuf(hashtype, U, seed->data, seed->len) );
457 /* mod 2**N . Step 7 will explicitly set the top bit to 1, so no need
458 * to handle mod 2**N-1 */
459 if (hashLen > N_bytes) {
460 offset = hashLen - N_bytes;
461 }
462 /* ******************************************************************
463 ** Step 7.
464 ** computed_q = 2**(N-1) + U + 1 - (U mod 2)
465 **
466 ** This is the same as:
467 ** computed_q = 2**(N-1) | U | 1;
468 */
469 U[offset] |= 0x80; /* U is MSB first */
470 U[hashLen-1] |= 0x01;
471 err = mp_read_unsigned_octets(Q, &U[offset], N_bytes);
472 cleanup:
473 memset(U, 0, HASH_LENGTH_MAX);
474 if (err) {
475 MP_TO_SEC_ERROR(err);
476 return SECFailure;
477 }
478 return rv;
479 }
480
481 /*
482 ** Perform steps from FIPS 186-3, Appendix A.1.2.1 and Appendix C.6
483 **
484 ** This generates a provable prime from two smaller prime. The resulting
485 ** prime p will have q0 as a multiple of p-1. q0 can be 1.
486 **
487 ** This implments steps 4 thorough 22 of FIPS 186-3 A.1.2.1 and
488 ** steps 16 through 34 of FIPS 186-2 C.6
489 */
490 #define MAX_ST_SEED_BITS HASH_LENGTH_MAX*BITS_PER_BYTE
491 SECStatus
492 makePrimefromPrimesShaweTaylor(
493 HASH_HashType hashtype, /* selected Hashing algorithm */
494 unsigned int length, /* input. Length of prime in bits. */
495 mp_int * c0, /* seed prime */
496 mp_int * q, /* sub prime, can be 1 */
497 mp_int * prime, /* output. */
498 SECItem * prime_seed, /* input/output. */
499 int * prime_gen_counter) /* input/output. */
500 {
501 mp_int c;
502 mp_int c0_2;
503 mp_int t;
504 mp_int a;
505 mp_int z;
506 mp_int two_length_minus_1;
507 SECStatus rv = SECFailure;
508 int hashlen = HASH_ResultLen(hashtype);
509 int outlen = hashlen*BITS_PER_BYTE;
510 int offset;
511 unsigned char bit, mask;
512 /* x needs to hold roundup(L/outlen)*outlen.
513 * This can be no larger than L+outlen-1, So we set it's size to
514 * our max L + max outlen and know we are safe */
515 unsigned char x[DSA_MAX_P_BITS/8+HASH_LENGTH_MAX];
516 mp_err err = MP_OKAY;
517 int i;
518 int iterations;
519 int old_counter;
520
521 MP_DIGITS(&c) = 0;
522 MP_DIGITS(&c0_2) = 0;
523 MP_DIGITS(&t) = 0;
524 MP_DIGITS(&a) = 0;
525 MP_DIGITS(&z) = 0;
526 MP_DIGITS(&two_length_minus_1) = 0;
527 CHECK_MPI_OK( mp_init(&c) );
528 CHECK_MPI_OK( mp_init(&c0_2) );
529 CHECK_MPI_OK( mp_init(&t) );
530 CHECK_MPI_OK( mp_init(&a) );
531 CHECK_MPI_OK( mp_init(&z) );
532 CHECK_MPI_OK( mp_init(&two_length_minus_1) );
533
534
535 /*
536 ** There is a slight mapping of variable names depending on which
537 ** FIPS 186 steps are being carried out. The mapping is as follows:
538 ** variable A.1.2.1 C.6
539 ** c0 p0 c0
540 ** q q 1
541 ** c p c
542 ** c0_2 2*p0*q 2*c0
543 ** length L length
544 ** prime_seed pseed prime_seed
545 ** prime_gen_counter pgen_counter prime_gen_counter
546 **
547 ** Also note: or iterations variable is actually iterations+1, since
548 ** iterations+1 works better in C.
549 */
550
551 /* Step 4/16 iterations = ceiling(length/outlen)-1 */
552 iterations = (length+outlen-1)/outlen; /* NOTE: iterations +1 */
553 /* Step 5/17 old_counter = prime_gen_counter */
554 old_counter = *prime_gen_counter;
555 /*
556 ** Comment: Generate a pseudorandom integer x in the interval
557 ** [2**(lenght-1), 2**length].
558 **
559 ** Step 6/18 x = 0
560 */
561 PORT_Memset(x, 0, sizeof(x));
562 /*
563 ** Step 7/19 for i = 0 to iterations do
564 ** x = x + (HASH(prime_seed + i) * 2^(i*outlen))
565 */
566 for (i=0; i < iterations; i++) {
567 /* is bigger than prime_seed should get to */
568 CHECK_SEC_OK( addToSeedThenHash(hashtype, prime_seed, i,
569 MAX_ST_SEED_BITS,&x[(iterations - i - 1)*hashlen]));
570 }
571 /* Step 8/20 prime_seed = prime_seed + iterations + 1 */
572 CHECK_SEC_OK(addToSeed(prime_seed, iterations, MAX_ST_SEED_BITS,
573 prime_seed));
574 /*
575 ** Step 9/21 x = 2 ** (length-1) + x mod 2 ** (length-1)
576 **
577 ** This step mathematically sets the high bit and clears out
578 ** all the other bits higher than length. 'x' is stored
579 ** in the x array, MSB first. The above formula gives us an 'x'
580 ** which is length bytes long and has the high bit set. We also know
581 ** that length <= iterations*outlen since
582 ** iterations=ceiling(length/outlen). First we find the offset in
583 ** bytes into the array where the high bit is.
584 */
585 offset = (outlen*iterations - length)/BITS_PER_BYTE;
586 /* now we want to set the 'high bit', since length may not be a
587 * multiple of 8,*/
588 bit = 1 << ((length-1) & 0x7); /* select the proper bit in the byte */
589 /* we need to zero out the rest of the bits in the byte above */
590 mask = (bit-1);
591 /* now we set it */
592 x[offset] = (mask & x[offset]) | bit;
593 /*
594 ** Comment: Generate a candidate prime c in the interval
595 ** [2**(lenght-1), 2**length].
596 **
597 ** Step 10 t = ceiling(x/(2q(p0)))
598 ** Step 22 t = ceiling(x/(2(c0)))
599 */
600 CHECK_MPI_OK( mp_read_unsigned_octets(&t, &x[offset],
601 hashlen*iterations - offset ) ); /* t = x */
602 CHECK_MPI_OK( mp_mul(c0, q, &c0_2) ); /* c0_2 is now c0*q */
603 CHECK_MPI_OK( mp_add(&c0_2, &c0_2, &c0_2) ); /* c0_2 is now 2*q*c0 */
604 CHECK_MPI_OK( mp_add(&t, &c0_2, &t) ); /* t = x+2*q*c0 */
605 CHECK_MPI_OK( mp_sub_d(&t, (mp_digit) 1, &t) ); /* t = x+2*q*c0 -1 */
606 /* t = floor((x+2qc0-1)/2qc0) = ceil(x/2qc0) */
607 CHECK_MPI_OK( mp_div(&t, &c0_2, &t, NULL) );
608 /*
609 ** step 11: if (2tqp0 +1 > 2**length), then t = ceiling(2**(length-1)/2qp0)
610 ** step 12: t = 2tqp0 +1.
611 **
612 ** step 23: if (2tc0 +1 > 2**length), then t = ceiling(2**(length-1)/2c0)
613 ** step 24: t = 2tc0 +1.
614 */
615 CHECK_MPI_OK( mp_2expt(&two_length_minus_1, length-1) );
616 step_23:
617 CHECK_MPI_OK( mp_mul(&t, &c0_2, &c) ); /* c = t*2qc0 */
618 CHECK_MPI_OK( mp_add_d(&c, (mp_digit)1, &c) ); /* c= 2tqc0 + 1*/
619 if (mpl_significant_bits(&c) > length) { /* if c > 2**length */
620 CHECK_MPI_OK( mp_sub_d(&c0_2, (mp_digit) 1, &t) ); /* t = 2qc0-1 */
621 /* t = 2**(length-1) + 2qc0 -1 */
622 CHECK_MPI_OK( mp_add(&two_length_minus_1,&t, &t) );
623 /* t = floor((2**(length-1)+2qc0 -1)/2qco)
624 * = ceil(2**(lenght-2)/2qc0) */
625 CHECK_MPI_OK( mp_div(&t, &c0_2, &t, NULL) );
626 CHECK_MPI_OK( mp_mul(&t, &c0_2, &c) );
627 CHECK_MPI_OK( mp_add_d(&c, (mp_digit)1, &c) ); /* c= 2tqc0 + 1*/
628 }
629 /* Step 13/25 prime_gen_counter = prime_gen_counter + 1*/
630 (*prime_gen_counter)++;
631 /*
632 ** Comment: Test the candidate prime c for primality; first pick an
633 ** integer a between 2 and c-2.
634 **
635 ** Step 14/26 a=0
636 */
637 PORT_Memset(x, 0, sizeof(x)); /* use x for a */
638 /*
639 ** Step 15/27 for i = 0 to iterations do
640 ** a = a + (HASH(prime_seed + i) * 2^(i*outlen))
641 **
642 ** NOTE: we reuse the x array for 'a' initially.
643 */
644 for (i=0; i < iterations; i++) {
645 /* MAX_ST_SEED_BITS is bigger than prime_seed should get to */
646 CHECK_SEC_OK(addToSeedThenHash(hashtype, prime_seed, i,
647 MAX_ST_SEED_BITS,&x[(iterations - i - 1)*hashlen]));
648 }
649 /* Step 16/28 prime_seed = prime_seed + iterations + 1 */
650 CHECK_SEC_OK(addToSeed(prime_seed, iterations, MAX_ST_SEED_BITS,
651 prime_seed));
652 /* Step 17/29 a = 2 + (a mod (c-3)). */
653 CHECK_MPI_OK( mp_read_unsigned_octets(&a, x, iterations*hashlen) );
654 CHECK_MPI_OK( mp_sub_d(&c, (mp_digit) 3, &z) ); /* z = c -3 */
655 CHECK_MPI_OK( mp_mod(&a, &z, &a) ); /* a = a mod c -3 */
656 CHECK_MPI_OK( mp_add_d(&a, (mp_digit) 2, &a) ); /* a = 2 + a mod c -3 */
657 /*
658 ** Step 18 z = a**(2tq) mod p.
659 ** Step 30 z = a**(2t) mod c.
660 */
661 CHECK_MPI_OK( mp_mul(&t, q, &z) ); /* z = tq */
662 CHECK_MPI_OK( mp_add(&z, &z, &z) ); /* z = 2tq */
663 CHECK_MPI_OK( mp_exptmod(&a, &z, &c, &z) ); /* z = a**(2tq) mod c */
664 /*
665 ** Step 19 if (( 1 == GCD(z-1,p)) and ( 1 == z**p0 mod p )), then
666 ** Step 31 if (( 1 == GCD(z-1,c)) and ( 1 == z**c0 mod c )), then
667 */
668 CHECK_MPI_OK( mp_sub_d(&z, (mp_digit) 1, &a) );
669 CHECK_MPI_OK( mp_gcd(&a,&c,&a ));
670 if (mp_cmp_d(&a, (mp_digit)1) == 0) {
671 CHECK_MPI_OK( mp_exptmod(&z, c0, &c, &a) );
672 if (mp_cmp_d(&a, (mp_digit)1) == 0) {
673 /* Step 31.1 prime = c */
674 CHECK_MPI_OK( mp_copy(&c, prime) );
675 /*
676 ** Step 31.2 return Success, prime, prime_seed,
677 ** prime_gen_counter
678 */
679 rv = SECSuccess;
680 goto cleanup;
681 }
682 }
683 /*
684 ** Step 20/32 If (prime_gen_counter > 4 * length + old_counter then
685 ** return (FAILURE, 0, 0, 0).
686 ** NOTE: the test is reversed, so we fall through on failure to the
687 ** cleanup routine
688 */
689 if (*prime_gen_counter < (4*length + old_counter)) {
690 /* Step 21/33 t = t + 1 */
691 CHECK_MPI_OK( mp_add_d(&t, (mp_digit) 1, &t) );
692 /* Step 22/34 Go to step 23/11 */
693 goto step_23;
694 }
695
696 /* if (prime_gencont > (4*length + old_counter), fall through to failure */
697 rv = SECFailure; /* really is already set, but paranoia is good */
698
699 cleanup:
700 mp_clear(&c);
701 mp_clear(&c0_2);
702 mp_clear(&t);
703 mp_clear(&a);
704 mp_clear(&z);
705 mp_clear(&two_length_minus_1);
706 if (err) {
707 MP_TO_SEC_ERROR(err);
708 rv = SECFailure;
709 }
710 if (rv == SECFailure) {
711 mp_zero(prime);
712 if (prime_seed->data) {
713 SECITEM_FreeItem(prime_seed, PR_FALSE);
714 }
715 *prime_gen_counter = 0;
716 }
717 return rv;
718 }
719
720 /*
721 ** Perform steps from FIPS 186-3, Appendix C.6
722 **
723 ** This generates a provable prime from a seed
724 */
725 SECStatus
726 makePrimefromSeedShaweTaylor(
727 HASH_HashType hashtype, /* selected Hashing algorithm */
728 unsigned int length, /* input. Length of prime in bits. */
729 const SECItem * input_seed, /* input. */
730 mp_int * prime, /* output. */
731 SECItem * prime_seed, /* output. */
732 int * prime_gen_counter) /* output. */
733 {
734 mp_int c;
735 mp_int c0;
736 mp_int one;
737 SECStatus rv = SECFailure;
738 int hashlen = HASH_ResultLen(hashtype);
739 int outlen = hashlen*BITS_PER_BYTE;
740 int offset;
741 unsigned char bit, mask;
742 unsigned char x[HASH_LENGTH_MAX*2];
743 mp_digit dummy;
744 mp_err err = MP_OKAY;
745 int i;
746
747 MP_DIGITS(&c) = 0;
748 MP_DIGITS(&c0) = 0;
749 MP_DIGITS(&one) = 0;
750 CHECK_MPI_OK( mp_init(&c) );
751 CHECK_MPI_OK( mp_init(&c0) );
752 CHECK_MPI_OK( mp_init(&one) );
753
754 /* Step 1. if length < 2 then return (FAILURE, 0, 0, 0) */
755 if (length < 2) {
756 rv = SECFailure;
757 goto cleanup;
758 }
759 /* Step 2. if length >= 33 then goto step 14 */
760 if (length >= 33) {
761 mp_zero(&one);
762 CHECK_MPI_OK( mp_add_d(&one, (mp_digit) 1, &one) );
763
764 /* Step 14 (status, c0, prime_seed, prime_gen_counter) =
765 ** (ST_Random_Prime((ceil(length/2)+1, input_seed)
766 */
767 rv = makePrimefromSeedShaweTaylor(hashtype, (length+1)/2+1,
768 input_seed, &c0, prime_seed, prime_gen_counter);
769 /* Step 15 if FAILURE is returned, return (FAILURE, 0, 0, 0). */
770 if (rv != SECSuccess) {
771 goto cleanup;
772 }
773 /* Steps 16-34 */
774 rv = makePrimefromPrimesShaweTaylor(hashtype,length, &c0, &one,
775 prime, prime_seed, prime_gen_counter);
776 goto cleanup; /* we're done, one way or the other */
777 }
778 /* Step 3 prime_seed = input_seed */
779 CHECK_SEC_OK(SECITEM_CopyItem(NULL, prime_seed, input_seed));
780 /* Step 4 prime_gen_count = 0 */
781 *prime_gen_counter = 0;
782
783 step_5:
784 /* Step 5 c = Hash(prime_seed) xor Hash(prime_seed+1). */
785 CHECK_SEC_OK(HASH_HashBuf(hashtype, x, prime_seed->data, prime_seed->len) );
786 CHECK_SEC_OK(addToSeedThenHash(hashtype, prime_seed, 1,
787 MAX_ST_SEED_BITS, &x[hashlen]) );
788 for (i=0; i < hashlen; i++) {
789 x[i] = x[i] ^ x[i+hashlen];
790 }
791 /* Step 6 c = 2**length-1 + c mod 2**length-1 */
792 /* This step mathematically sets the high bit and clears out
793 ** all the other bits higher than length. Right now c is stored
794 ** in the x array, MSB first. The above formula gives us a c which
795 ** is length bytes long and has the high bit set. We also know that
796 ** length < outlen since the smallest outlen is 160 bits and the largest
797 ** length at this point is 32 bits. So first we find the offset in bytes
798 ** into the array where the high bit is.
799 */
800 offset = (outlen - length)/BITS_PER_BYTE;
801 /* now we want to set the 'high bit'. We have to calculate this since
802 * length may not be a multiple of 8.*/
803 bit = 1 << ((length-1) & 0x7); /* select the proper bit in the byte */
804 /* we need to zero out the rest of the bits in the byte above */
805 mask = (bit-1);
806 /* now we set it */
807 x[offset] = (mask & x[offset]) | bit;
808 /* Step 7 c = c*floor(c/2) + 1 */
809 /* set the low bit. much easier to find (the end of the array) */
810 x[hashlen-1] |= 1;
811 /* now that we've set our bits, we can create our candidate "c" */
812 CHECK_MPI_OK( mp_read_unsigned_octets(&c, &x[offset], hashlen-offset) );
813 /* Step 8 prime_gen_counter = prime_gen_counter + 1 */
814 (*prime_gen_counter)++;
815 /* Step 9 prime_seed = prime_seed + 2 */
816 CHECK_SEC_OK(addToSeed(prime_seed, 2, MAX_ST_SEED_BITS, prime_seed));
817 /* Step 10 Perform deterministic primality test on c. For example, since
818 ** c is small, it's primality can be tested by trial division, See
819 ** See Appendic C.7.
820 **
821 ** We in fact test with trial division. mpi has a built int trial divider
822 ** that divides all divisors up to 2^16.
823 */
824 if (prime_tab[prime_tab_size-1] < 0xFFF1) {
825 /* we aren't testing all the primes between 0 and 2^16, we really
826 * can't use this construction. Just fail. */
827 rv = SECFailure;
828 goto cleanup;
829 }
830 dummy = prime_tab_size;
831 err = mpp_divis_primes(&c, &dummy);
832 /* Step 11 if c is prime then */
833 if (err == MP_NO) {
834 /* Step 11.1 prime = c */
835 CHECK_MPI_OK( mp_copy(&c, prime) );
836 /* Step 11.2 return SUCCESS prime, prime_seed, prime_gen_counter */
837 err = MP_OKAY;
838 rv = SECSuccess;
839 goto cleanup;
840 } else if (err != MP_YES) {
841 goto cleanup; /* function failed, bail out */
842 } else {
843 /* reset mp_err */
844 err = MP_OKAY;
845 }
846 /*
847 ** Step 12 if (prime_gen_counter > (4*len))
848 ** then return (FAILURE, 0, 0, 0))
849 ** Step 13 goto step 5
850 */
851 if (*prime_gen_counter <= (4*length)) {
852 goto step_5;
853 }
854 /* if (prime_gencont > 4*length), fall through to failure */
855 rv = SECFailure; /* really is already set, but paranoia is good */
856
857 cleanup:
858 mp_clear(&c);
859 mp_clear(&c0);
860 mp_clear(&one);
861 if (err) {
862 MP_TO_SEC_ERROR(err);
863 rv = SECFailure;
864 }
865 if (rv == SECFailure) {
866 mp_zero(prime);
867 if (prime_seed->data) {
868 SECITEM_FreeItem(prime_seed, PR_FALSE);
869 }
870 *prime_gen_counter = 0;
871 }
872 return rv;
873 }
874
875
876 /*
877 * Find a Q and algorithm from Seed.
878 */
879 static SECStatus
880 findQfromSeed(
881 unsigned int L, /* input. Length of p in bits. */
882 unsigned int N, /* input. Length of q in bits. */
883 unsigned int g, /* input. Length of seed in bits. */
884 const SECItem * seed, /* input. */
885 mp_int * Q, /* input. */
886 mp_int * Q_, /* output. */
887 int * qseed_len, /* output */
888 HASH_HashType *hashtypePtr, /* output. Hash uses */
889 pqgGenType *typePtr) /* output. Generation Type used */
890 {
891 HASH_HashType hashtype;
892 SECItem firstseed = { 0, 0, 0 };
893 SECItem qseed = { 0, 0, 0 };
894 SECStatus rv;
895
896 *qseed_len = 0; /* only set if FIPS186_3_ST_TYPE */
897
898 /* handle legacy small DSA first can only be FIPS186_1_TYPE */
899 if (L < 1024) {
900 rv =makeQfromSeed(g,seed,Q_);
901 if ((rv == SECSuccess) && (mp_cmp(Q,Q_) == 0)) {
902 *hashtypePtr = HASH_AlgSHA1;
903 *typePtr = FIPS186_1_TYPE;
904 return SECSuccess;
905 }
906 return SECFailure;
907 }
908 /* 1024 could use FIPS186_1 or FIPS186_3 algorithms, we need to try
909 * them both */
910 if (L == 1024) {
911 rv = makeQfromSeed(g,seed,Q_);
912 if (rv == SECSuccess) {
913 if (mp_cmp(Q,Q_) == 0) {
914 *hashtypePtr = HASH_AlgSHA1;
915 *typePtr = FIPS186_1_TYPE;
916 return SECSuccess;
917 }
918 }
919 /* fall through for FIPS186_3 types */
920 }
921 /* at this point we know we aren't using FIPS186_1, start trying FIPS186_3
922 * with appropriate hash types */
923 for (hashtype = getFirstHash(L,N); hashtype != HASH_AlgTOTAL;
924 hashtype=getNextHash(hashtype)) {
925 rv = makeQ2fromSeed(hashtype, N, seed, Q_);
926 if (rv != SECSuccess) {
927 continue;
928 }
929 if (mp_cmp(Q,Q_) == 0) {
930 *hashtypePtr = hashtype;
931 *typePtr = FIPS186_3_TYPE;
932 return SECSuccess;
933 }
934 }
935 /*
936 * OK finally try FIPS186_3 Shawe-Taylor
937 */
938 firstseed = *seed;
939 firstseed.len = seed->len/3;
940 for (hashtype = getFirstHash(L,N); hashtype != HASH_AlgTOTAL;
941 hashtype=getNextHash(hashtype)) {
942 int count;
943
944 rv = makePrimefromSeedShaweTaylor(hashtype, N, &firstseed, Q_,
945 &qseed, &count);
946 if (rv != SECSuccess) {
947 continue;
948 }
949 if (mp_cmp(Q,Q_) == 0) {
950 /* check qseed as well... */
951 int offset = seed->len - qseed.len;
952 if ((offset < 0) ||
953 (PORT_Memcmp(&seed->data[offset],qseed.data,qseed.len) != 0)) {
954 /* we found q, but the seeds don't match. This isn't an
955 * accident, someone has been tweeking with the seeds, just
956 * fail a this point. */
957 SECITEM_FreeItem(&qseed,PR_FALSE);
958 return SECFailure;
959 }
960 *qseed_len = qseed.len;
961 *hashtypePtr = hashtype;
962 *typePtr = FIPS186_3_ST_TYPE;
963 SECITEM_FreeItem(&qseed, PR_FALSE);
964 return SECSuccess;
965 }
966 SECITEM_FreeItem(&qseed, PR_FALSE);
967 }
968 /* no hash algorithms found which match seed to Q, fail */
969 return SECFailure;
970 }
971
972
973
974 /*
975 ** Perform steps 7, 8 and 9 of FIPS 186, appendix 2.2.
976 ** which are the same as steps 11.1-11.5 of FIPS 186-2, App A.1.1.2
977 ** Generate P from Q, seed, L, and offset.
978 */
979 static SECStatus
980 makePfromQandSeed(
981 HASH_HashType hashtype, /* selected Hashing algorithm */
982 unsigned int L, /* Length of P in bits. Per FIPS 186. */
983 unsigned int N, /* Length of Q in bits. Per FIPS 186. */
984 unsigned int offset, /* Per FIPS 186, App 2.2. & 186-3 App A.1.1.2 */
985 unsigned int seedlen, /* input. Length of seed in bits. (g in 186-1)*/
986 const SECItem * seed, /* input. */
987 const mp_int * Q, /* input. */
988 mp_int * P) /* output. */
989 {
990 unsigned int j; /* Per FIPS 186-3 App. A.1.1.2 (k in 186-1)*/
991 unsigned int n; /* Per FIPS 186, appendix 2.2. */
992 mp_digit b; /* Per FIPS 186, appendix 2.2. */
993 unsigned int outlen; /* Per FIPS 186-3 App. A.1.1.2 */
994 unsigned int hashlen; /* outlen in bytes */
995 unsigned char V_j[HASH_LENGTH_MAX];
996 mp_int W, X, c, twoQ, V_n, tmp;
997 mp_err err = MP_OKAY;
998 SECStatus rv = SECSuccess;
999 /* Initialize bignums */
1000 MP_DIGITS(&W) = 0;
1001 MP_DIGITS(&X) = 0;
1002 MP_DIGITS(&c) = 0;
1003 MP_DIGITS(&twoQ) = 0;
1004 MP_DIGITS(&V_n) = 0;
1005 MP_DIGITS(&tmp) = 0;
1006 CHECK_MPI_OK( mp_init(&W) );
1007 CHECK_MPI_OK( mp_init(&X) );
1008 CHECK_MPI_OK( mp_init(&c) );
1009 CHECK_MPI_OK( mp_init(&twoQ) );
1010 CHECK_MPI_OK( mp_init(&tmp) );
1011 CHECK_MPI_OK( mp_init(&V_n) );
1012
1013 hashlen = HASH_ResultLen(hashtype);
1014 outlen = hashlen*BITS_PER_BYTE;
1015
1016 /* L - 1 = n*outlen + b */
1017 n = (L - 1) / outlen;
1018 b = (L - 1) % outlen;
1019
1020 /* ******************************************************************
1021 ** Step 11.1 (Step 7 in 186-1)
1022 ** "for j = 0 ... n let
1023 ** V_j = SHA[(SEED + offset + j) mod 2**seedlen]."
1024 **
1025 ** Step 11.2 (Step 8 in 186-1)
1026 ** "W = V_0 + (V_1 * 2**outlen) + ... + (V_n-1 * 2**((n-1)*outlen))
1027 ** + ((V_n mod 2**b) * 2**(n*outlen))
1028 */
1029 for (j=0; j<n; ++j) { /* Do the first n terms of V_j */
1030 /* Do step 11.1 for iteration j.
1031 ** V_j = HASH[(seed + offset + j) mod 2**g]
1032 */
1033 CHECK_SEC_OK( addToSeedThenHash(hashtype,seed,offset+j, seedlen, V_j) );
1034 /* Do step 11.2 for iteration j.
1035 ** W += V_j * 2**(j*outlen)
1036 */
1037 OCTETS_TO_MPINT(V_j, &tmp, hashlen); /* get bignum V_j */
1038 CHECK_MPI_OK( mpl_lsh(&tmp, &tmp, j*outlen) );/* tmp=V_j << j*outlen */
1039 CHECK_MPI_OK( mp_add(&W, &tmp, &W) ); /* W += tmp */
1040 }
1041 /* Step 11.2, continued.
1042 ** [W += ((V_n mod 2**b) * 2**(n*outlen))]
1043 */
1044 CHECK_SEC_OK( addToSeedThenHash(hashtype, seed, offset + n, seedlen, V_j) );
1045 OCTETS_TO_MPINT(V_j, &V_n, hashlen); /* get bignum V_n */
1046 CHECK_MPI_OK( mp_div_2d(&V_n, b, NULL, &tmp) ); /* tmp = V_n mod 2**b */
1047 CHECK_MPI_OK( mpl_lsh(&tmp, &tmp, n*outlen) ); /* tmp = tmp << n*outlen */
1048 CHECK_MPI_OK( mp_add(&W, &tmp, &W) ); /* W += tmp */
1049 /* Step 11.3, (Step 8 in 186-1)
1050 ** "X = W + 2**(L-1).
1051 ** Note that 0 <= W < 2**(L-1) and hence 2**(L-1) <= X < 2**L."
1052 */
1053 CHECK_MPI_OK( mpl_set_bit(&X, (mp_size)(L-1), 1) ); /* X = 2**(L-1) */
1054 CHECK_MPI_OK( mp_add(&X, &W, &X) ); /* X += W */
1055 /*************************************************************
1056 ** Step 11.4. (Step 9 in 186-1)
1057 ** "c = X mod 2q"
1058 */
1059 CHECK_MPI_OK( mp_mul_2(Q, &twoQ) ); /* 2q */
1060 CHECK_MPI_OK( mp_mod(&X, &twoQ, &c) ); /* c = X mod 2q */
1061 /*************************************************************
1062 ** Step 11.5. (Step 9 in 186-1)
1063 ** "p = X - (c - 1).
1064 ** Note that p is congruent to 1 mod 2q."
1065 */
1066 CHECK_MPI_OK( mp_sub_d(&c, 1, &c) ); /* c -= 1 */
1067 CHECK_MPI_OK( mp_sub(&X, &c, P) ); /* P = X - c */
1068 cleanup:
1069 mp_clear(&W);
1070 mp_clear(&X);
1071 mp_clear(&c);
1072 mp_clear(&twoQ);
1073 mp_clear(&V_n);
1074 mp_clear(&tmp);
1075 if (err) {
1076 MP_TO_SEC_ERROR(err);
1077 return SECFailure;
1078 }
1079 return rv;
1080 }
1081
1082 /*
1083 ** Generate G from h, P, and Q.
1084 */
1085 static SECStatus
1086 makeGfromH(const mp_int *P, /* input. */
1087 const mp_int *Q, /* input. */
1088 mp_int *H, /* input and output. */
1089 mp_int *G, /* output. */
1090 PRBool *passed)
1091 {
1092 mp_int exp, pm1;
1093 mp_err err = MP_OKAY;
1094 SECStatus rv = SECSuccess;
1095 *passed = PR_FALSE;
1096 MP_DIGITS(&exp) = 0;
1097 MP_DIGITS(&pm1) = 0;
1098 CHECK_MPI_OK( mp_init(&exp) );
1099 CHECK_MPI_OK( mp_init(&pm1) );
1100 CHECK_MPI_OK( mp_sub_d(P, 1, &pm1) ); /* P - 1 */
1101 if ( mp_cmp(H, &pm1) >= 0) /* H >= P-1 */
1102 CHECK_MPI_OK( mp_sub(H, &pm1, H) ); /* H = H mod (P-1) */
1103 /* Let b = 2**n (smallest power of 2 greater than P).
1104 ** Since P-1 >= b/2, and H < b, quotient(H/(P-1)) = 0 or 1
1105 ** so the above operation safely computes H mod (P-1)
1106 */
1107 /* Check for H = to 0 or 1. Regen H if so. (Regen means return error). */
1108 if (mp_cmp_d(H, 1) <= 0) {
1109 rv = SECFailure;
1110 goto cleanup;
1111 }
1112 /* Compute G, according to the equation G = (H ** ((P-1)/Q)) mod P */
1113 CHECK_MPI_OK( mp_div(&pm1, Q, &exp, NULL) ); /* exp = (P-1)/Q */
1114 CHECK_MPI_OK( mp_exptmod(H, &exp, P, G) ); /* G = H ** exp mod P */
1115 /* Check for G == 0 or G == 1, return error if so. */
1116 if (mp_cmp_d(G, 1) <= 0) {
1117 rv = SECFailure;
1118 goto cleanup;
1119 }
1120 *passed = PR_TRUE;
1121 cleanup:
1122 mp_clear(&exp);
1123 mp_clear(&pm1);
1124 if (err) {
1125 MP_TO_SEC_ERROR(err);
1126 rv = SECFailure;
1127 }
1128 return rv;
1129 }
1130
1131 /*
1132 ** Generate G from seed, index, P, and Q.
1133 */
1134 static SECStatus
1135 makeGfromIndex(HASH_HashType hashtype,
1136 const mp_int *P, /* input. */
1137 const mp_int *Q, /* input. */
1138 const SECItem *seed, /* input. */
1139 unsigned char index, /* input. */
1140 mp_int *G) /* input/output */
1141 {
1142 mp_int e, pm1, W;
1143 unsigned int count;
1144 unsigned char data[HASH_LENGTH_MAX];
1145 unsigned int len;
1146 mp_err err = MP_OKAY;
1147 SECStatus rv = SECSuccess;
1148 const SECHashObject *hashobj;
1149 void *hashcx = NULL;
1150
1151 MP_DIGITS(&e) = 0;
1152 MP_DIGITS(&pm1) = 0;
1153 MP_DIGITS(&W) = 0;
1154 CHECK_MPI_OK( mp_init(&e) );
1155 CHECK_MPI_OK( mp_init(&pm1) );
1156 CHECK_MPI_OK( mp_init(&W) );
1157
1158 /* initialize our hash stuff */
1159 hashobj = HASH_GetRawHashObject(hashtype);
1160 if (hashobj == NULL) {
1161 /* shouldn't happen */
1162 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1163 rv = SECFailure;
1164 goto cleanup;
1165 }
1166 hashcx = hashobj->create();
1167 if (hashcx == NULL) {
1168 rv = SECFailure;
1169 goto cleanup;
1170 }
1171
1172 CHECK_MPI_OK( mp_sub_d(P, 1, &pm1) ); /* P - 1 */
1173 /* Step 3 e = (p-1)/q */
1174 CHECK_MPI_OK( mp_div(&pm1, Q, &e, NULL) ); /* e = (P-1)/Q */
1175 /* Steps 4, 5, and 6 */
1176 /* count is a 16 bit value in the spec. We actually represent count
1177 * as more than 16 bits so we can easily detect the 16 bit overflow */
1178 #define MAX_COUNT 0x10000
1179 for (count = 1; count < MAX_COUNT; count++) {
1180 /* step 7
1181 * U = domain_param_seed || "ggen" || index || count
1182 * step 8
1183 * W = HASH(U)
1184 */
1185 hashobj->begin(hashcx);
1186 hashobj->update(hashcx,seed->data,seed->len);
1187 hashobj->update(hashcx, (unsigned char *)"ggen", 4);
1188 hashobj->update(hashcx,&index, 1);
1189 data[0] = (count >> 8) & 0xff;
1190 data[1] = count & 0xff;
1191 hashobj->update(hashcx, data, 2);
1192 hashobj->end(hashcx, data, &len, sizeof(data));
1193 OCTETS_TO_MPINT(data, &W, len);
1194 /* step 9. g = W**e mod p */
1195 CHECK_MPI_OK( mp_exptmod(&W, &e, P, G) );
1196 /* step 10. if (g < 2) then goto step 5 */
1197 /* NOTE: this weird construct is to keep the flow according to the spec.
1198 * the continue puts us back to step 5 of the for loop */
1199 if (mp_cmp_d(G, 2) < 0) {
1200 continue;
1201 }
1202 break; /* step 11 follows step 10 if the test condition is false */
1203 }
1204 if (count >= MAX_COUNT) {
1205 rv = SECFailure; /* last part of step 6 */
1206 }
1207 /* step 11.
1208 * return valid G */
1209 cleanup:
1210 PORT_Memset(data, 0, sizeof(data));
1211 if (hashcx) {
1212 hashobj->destroy(hashcx, PR_TRUE);
1213 }
1214 mp_clear(&e);
1215 mp_clear(&pm1);
1216 mp_clear(&W);
1217 if (err) {
1218 MP_TO_SEC_ERROR(err);
1219 rv = SECFailure;
1220 }
1221 return rv;
1222 }
1223
1224 /* This code uses labels and gotos, so that it can follow the numbered
1225 ** steps in the algorithms from FIPS 186-3 appendix A.1.1.2 very closely,
1226 ** and so that the correctness of this code can be easily verified.
1227 ** So, please forgive the ugly c code.
1228 **/
1229 static SECStatus
1230 pqg_ParamGen(unsigned int L, unsigned int N, pqgGenType type,
1231 unsigned int seedBytes, PQGParams **pParams, PQGVerify **pVfy)
1232 {
1233 unsigned int n; /* Per FIPS 186, app 2.2. 186-3 app A.1.1.2 */
1234 unsigned int b; /* Per FIPS 186, app 2.2. 186-3 app A.1.1.2 */
1235 unsigned int seedlen; /* Per FIPS 186-3 app A.1.1.2 (was 'g' 186-1)*/
1236 unsigned int counter; /* Per FIPS 186, app 2.2. 186-3 app A.1.1.2 */
1237 unsigned int offset; /* Per FIPS 186, app 2.2. 186-3 app A.1.1.2 */
1238 unsigned int outlen; /* Per FIPS 186-3, appendix A.1.1.2. */
1239 unsigned int maxCount;
1240 HASH_HashType hashtype;
1241 SECItem *seed; /* Per FIPS 186, app 2.2. 186-3 app A.1.1.2 */
1242 PRArenaPool *arena = NULL;
1243 PQGParams *params = NULL;
1244 PQGVerify *verify = NULL;
1245 PRBool passed;
1246 SECItem hit = { 0, 0, 0 };
1247 SECItem firstseed = { 0, 0, 0 };
1248 SECItem qseed = { 0, 0, 0 };
1249 SECItem pseed = { 0, 0, 0 };
1250 mp_int P, Q, G, H, l, p0;
1251 mp_err err = MP_OKAY;
1252 SECStatus rv = SECFailure;
1253 int iterations = 0;
1254
1255
1256 /* Step 1. L and N already checked by caller*/
1257 /* Step 2. if (seedlen < N) return INVALID; */
1258 if (seedBytes < N/BITS_PER_BYTE || !pParams || !pVfy) {
1259 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1260 return SECFailure;
1261 }
1262 /* Initialize an arena for the params. */
1263 arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
1264 if (!arena) {
1265 PORT_SetError(SEC_ERROR_NO_MEMORY);
1266 return SECFailure;
1267 }
1268 params = (PQGParams *)PORT_ArenaZAlloc(arena, sizeof(PQGParams));
1269 if (!params) {
1270 PORT_SetError(SEC_ERROR_NO_MEMORY);
1271 PORT_FreeArena(arena, PR_TRUE);
1272 return SECFailure;
1273 }
1274 params->arena = arena;
1275 /* Initialize an arena for the verify. */
1276 arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
1277 if (!arena) {
1278 PORT_SetError(SEC_ERROR_NO_MEMORY);
1279 PORT_FreeArena(params->arena, PR_TRUE);
1280 return SECFailure;
1281 }
1282 verify = (PQGVerify *)PORT_ArenaZAlloc(arena, sizeof(PQGVerify));
1283 if (!verify) {
1284 PORT_SetError(SEC_ERROR_NO_MEMORY);
1285 PORT_FreeArena(arena, PR_TRUE);
1286 PORT_FreeArena(params->arena, PR_TRUE);
1287 return SECFailure;
1288 }
1289 verify->arena = arena;
1290 seed = &verify->seed;
1291 arena = NULL;
1292 /* Initialize bignums */
1293 MP_DIGITS(&P) = 0;
1294 MP_DIGITS(&Q) = 0;
1295 MP_DIGITS(&G) = 0;
1296 MP_DIGITS(&H) = 0;
1297 MP_DIGITS(&l) = 0;
1298 MP_DIGITS(&p0) = 0;
1299 CHECK_MPI_OK( mp_init(&P) );
1300 CHECK_MPI_OK( mp_init(&Q) );
1301 CHECK_MPI_OK( mp_init(&G) );
1302 CHECK_MPI_OK( mp_init(&H) );
1303 CHECK_MPI_OK( mp_init(&l) );
1304 CHECK_MPI_OK( mp_init(&p0) );
1305
1306 /* Select Hash and Compute lengths. */
1307 /* getFirstHash gives us the smallest acceptable hash for this key
1308 * strength */
1309 hashtype = getFirstHash(L,N);
1310 outlen = HASH_ResultLen(hashtype)*BITS_PER_BYTE;
1311
1312 /* Step 3: n = Ceil(L/outlen)-1; (same as n = Floor((L-1)/outlen)) */
1313 n = (L - 1) / outlen;
1314 /* Step 4: b = L -1 - (n*outlen); (same as n = (L-1) mod outlen) */
1315 b = (L - 1) % outlen;
1316 seedlen = seedBytes * BITS_PER_BYTE; /* bits in seed */
1317 step_5:
1318 /* ******************************************************************
1319 ** Step 5. (Step 1 in 186-1)
1320 ** "Choose an abitrary sequence of at least N bits and call it SEED.
1321 ** Let g be the length of SEED in bits."
1322 */
1323 if (++iterations > MAX_ITERATIONS) { /* give up after a while */
1324 PORT_SetError(SEC_ERROR_NEED_RANDOM);
1325 goto cleanup;
1326 }
1327 seed->len = seedBytes;
1328 CHECK_SEC_OK( getPQseed(seed, verify->arena) );
1329 /* ******************************************************************
1330 ** Step 6. (Step 2 in 186-1)
1331 **
1332 ** "Compute U = SHA[SEED] XOR SHA[(SEED+1) mod 2**g]. (186-1)"
1333 ** "Compute U = HASH[SEED] 2**(N-1). (186-3)"
1334 **
1335 ** Step 7. (Step 3 in 186-1)
1336 ** "Form Q from U by setting the most signficant bit (the 2**159 bit)
1337 ** and the least signficant bit to 1. In terms of boolean operations,
1338 ** Q = U OR 2**159 OR 1. Note that 2**159 < Q < 2**160. (186-1)"
1339 **
1340 ** "q = 2**(N-1) + U + 1 - (U mod 2) (186-3)
1341 **
1342 ** Note: Both formulations are the same for U < 2**(N-1) and N=160
1343 **
1344 ** If using Shawe-Taylor, We do the entire A.1.2.1.2 setps in the block
1345 ** FIPS186_3_ST_TYPE.
1346 */
1347 if (type == FIPS186_1_TYPE) {
1348 CHECK_SEC_OK( makeQfromSeed(seedlen, seed, &Q) );
1349 } else if (type == FIPS186_3_TYPE) {
1350 CHECK_SEC_OK( makeQ2fromSeed(hashtype, N, seed, &Q) );
1351 } else {
1352 /* FIPS186_3_ST_TYPE */
1353 int qgen_counter, pgen_counter;
1354
1355 /* Step 1 (L,N) already checked for acceptability */
1356
1357 firstseed = *seed;
1358 qgen_counter = 0;
1359 /* Step 2. Use N and firstseed to generate random prime q
1360 * using Apendix C.6 */
1361 CHECK_SEC_OK( makePrimefromSeedShaweTaylor(hashtype, N, &firstseed, &Q,
1362 &qseed, &qgen_counter) );
1363 /* Step 3. Use floor(L/2+1) and qseed to generate random prime p0
1364 * using Appendix C.6 */
1365 pgen_counter = 0;
1366 CHECK_SEC_OK( makePrimefromSeedShaweTaylor(hashtype, (L+1)/2+1,
1367 &qseed, &p0, &pseed, &pgen_counter) );
1368 /* Steps 4-22 FIPS 186-3 appendix A.1.2.1.2 */
1369 CHECK_SEC_OK( makePrimefromPrimesShaweTaylor(hashtype, L,
1370 &p0, &Q, &P, &pseed, &pgen_counter) );
1371
1372 /* combine all the seeds */
1373 seed->len = firstseed.len +qseed.len + pseed.len;
1374 seed->data = PORT_ArenaZAlloc(verify->arena, seed->len);
1375 if (seed->data == NULL) {
1376 goto cleanup;
1377 }
1378 PORT_Memcpy(seed->data, firstseed.data, firstseed.len);
1379 PORT_Memcpy(seed->data+firstseed.len, pseed.data, pseed.len);
1380 PORT_Memcpy(seed->data+firstseed.len+pseed.len, qseed.data, qseed.len);
1381 counter = 0 ; /* (qgen_counter << 16) | pgen_counter; */
1382
1383 /* we've generated both P and Q now, skip to generating G */
1384 goto generate_G;
1385 }
1386 /* ******************************************************************
1387 ** Step 8. (Step 4 in 186-1)
1388 ** "Use a robust primality testing algorithm to test whether q is prime."
1389 **
1390 ** Appendix 2.1 states that a Rabin test with at least 50 iterations
1391 ** "will give an acceptable probability of error."
1392 */
1393 /*CHECK_SEC_OK( prm_RabinTest(&Q, &passed) );*/
1394 err = mpp_pprime(&Q, prime_testcount_q(L,N));
1395 passed = (err == MP_YES) ? SECSuccess : SECFailure;
1396 /* ******************************************************************
1397 ** Step 9. (Step 5 in 186-1) "If q is not prime, goto step 5 (1 in 186-1)."
1398 */
1399 if (passed != SECSuccess)
1400 goto step_5;
1401 /* ******************************************************************
1402 ** Step 10.
1403 ** offset = 1;
1404 **( Step 6b 186-1)"Let counter = 0 and offset = 2."
1405 */
1406 offset = (type == FIPS186_1_TYPE) ? 2 : 1;
1407 /*
1408 ** Step 11. (Step 6a,13a,14 in 186-1)
1409 ** For counter - 0 to (4L-1) do
1410 **
1411 */
1412 maxCount = L >= 1024 ? (4*L - 1) : 4095;
1413 for (counter = 0; counter <= maxCount; counter++) {
1414 /* ******************************************************************
1415 ** Step 11.1 (Step 7 in 186-1)
1416 ** "for j = 0 ... n let
1417 ** V_j = HASH[(SEED + offset + j) mod 2**seedlen]."
1418 **
1419 ** Step 11.2 (Step 8 in 186-1)
1420 ** "W = V_0 + V_1*2**outlen+...+ V_n-1 * 2**((n-1)*outlen) +
1421 ** ((Vn* mod 2**b)*2**(n*outlen))"
1422 ** Step 11.3 (Step 8 in 186-1)
1423 ** "X = W + 2**(L-1)
1424 ** Note that 0 <= W < 2**(L-1) and hence 2**(L-1) <= X < 2**L."
1425 **
1426 ** Step 11.4 (Step 9 in 186-1).
1427 ** "c = X mod 2q"
1428 **
1429 ** Step 11.5 (Step 9 in 186-1).
1430 ** " p = X - (c - 1).
1431 ** Note that p is congruent to 1 mod 2q."
1432 */
1433 CHECK_SEC_OK( makePfromQandSeed(hashtype, L, N, offset, seedlen,
1434 seed, &Q, &P) );
1435 /*************************************************************
1436 ** Step 11.6. (Step 10 in 186-1)
1437 ** "if p < 2**(L-1), then goto step 11.9. (step 13 in 186-1)"
1438 */
1439 CHECK_MPI_OK( mpl_set_bit(&l, (mp_size)(L-1), 1) ); /* l = 2**(L-1) */
1440 if (mp_cmp(&P, &l) < 0)
1441 goto step_11_9;
1442 /************************************************************
1443 ** Step 11.7 (step 11 in 186-1)
1444 ** "Perform a robust primality test on p."
1445 */
1446 /*CHECK_SEC_OK( prm_RabinTest(&P, &passed) );*/
1447 err = mpp_pprime(&P, prime_testcount_p(L, N));
1448 passed = (err == MP_YES) ? SECSuccess : SECFailure;
1449 /* ******************************************************************
1450 ** Step 11.8. "If p is determined to be primed return VALID
1451 ** values of p, q, seed and counter."
1452 */
1453 if (passed == SECSuccess)
1454 break;
1455 step_11_9:
1456 /* ******************************************************************
1457 ** Step 11.9. "offset = offset + n + 1."
1458 */
1459 offset += n + 1;
1460 }
1461 /* ******************************************************************
1462 ** Step 12. "goto step 5."
1463 **
1464 ** NOTE: if counter <= maxCount, then we exited the loop at Step 11.8
1465 ** and now need to return p,q, seed, and counter.
1466 */
1467 if (counter > maxCount)
1468 goto step_5;
1469
1470 generate_G:
1471 /* ******************************************************************
1472 ** returning p, q, seed and counter
1473 */
1474 if (type == FIPS186_1_TYPE) {
1475 /* Generate g, This is called the "Unverifiable Generation of g
1476 * in FIPA186-3 Appedix A.2.1. For compatibility we maintain
1477 * this version of the code */
1478 SECITEM_AllocItem(NULL, &hit, L/8); /* h is no longer than p */
1479 if (!hit.data) goto cleanup;
1480 do {
1481 /* loop generate h until 1<h<p-1 and (h**[(p-1)/q])mod p > 1 */
1482 CHECK_SEC_OK( generate_h_candidate(&hit, &H) );
1483 CHECK_SEC_OK( makeGfromH(&P, &Q, &H, &G, &passed) );
1484 } while (passed != PR_TRUE);
1485 MPINT_TO_SECITEM(&H, &verify->h, verify->arena);
1486 } else {
1487 unsigned char index = 1; /* default to 1 */
1488 verify->h.data = (unsigned char *)PORT_ArenaZAlloc(verify->arena, 1);
1489 if (verify->h.data == NULL) { goto cleanup; }
1490 verify->h.len = 1;
1491 verify->h.data[0] = index;
1492 /* Generate g, using the FIPS 186-3 Appendix A.23 */
1493 CHECK_SEC_OK(makeGfromIndex(hashtype, &P, &Q, seed, index, &G) );
1494 }
1495 /* All generation is done. Now, save the PQG params. */
1496 MPINT_TO_SECITEM(&P, &params->prime, params->arena);
1497 MPINT_TO_SECITEM(&Q, &params->subPrime, params->arena);
1498 MPINT_TO_SECITEM(&G, &params->base, params->arena);
1499 verify->counter = counter;
1500 *pParams = params;
1501 *pVfy = verify;
1502 cleanup:
1503 if (pseed.data) {
1504 PORT_Free(pseed.data);
1505 }
1506 if (qseed.data) {
1507 PORT_Free(qseed.data);
1508 }
1509 mp_clear(&P);
1510 mp_clear(&Q);
1511 mp_clear(&G);
1512 mp_clear(&H);
1513 mp_clear(&l);
1514 mp_clear(&p0);
1515 if (err) {
1516 MP_TO_SEC_ERROR(err);
1517 rv = SECFailure;
1518 }
1519 if (rv) {
1520 PORT_FreeArena(params->arena, PR_TRUE);
1521 PORT_FreeArena(verify->arena, PR_TRUE);
1522 }
1523 if (hit.data) {
1524 SECITEM_FreeItem(&hit, PR_FALSE);
1525 }
1526 return rv;
1527 }
1528
1529 SECStatus
1530 PQG_ParamGen(unsigned int j, PQGParams **pParams, PQGVerify **pVfy)
1531 {
1532 unsigned int L; /* Length of P in bits. Per FIPS 186. */
1533 unsigned int seedBytes;
1534
1535 if (j > 8 || !pParams || !pVfy) {
1536 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1537 return SECFailure;
1538 }
1539 L = 512 + (j * 64); /* bits in P */
1540 seedBytes = L/8;
1541 return pqg_ParamGen(L, DSA1_Q_BITS, FIPS186_1_TYPE, seedBytes,
1542 pParams, pVfy);
1543 }
1544
1545 SECStatus
1546 PQG_ParamGenSeedLen(unsigned int j, unsigned int seedBytes,
1547 PQGParams **pParams, PQGVerify **pVfy)
1548 {
1549 unsigned int L; /* Length of P in bits. Per FIPS 186. */
1550
1551 if (j > 8 || !pParams || !pVfy) {
1552 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1553 return SECFailure;
1554 }
1555 L = 512 + (j * 64); /* bits in P */
1556 return pqg_ParamGen(L, DSA1_Q_BITS, FIPS186_1_TYPE, seedBytes,
1557 pParams, pVfy);
1558 }
1559
1560 SECStatus
1561 PQG_ParamGenV2(unsigned int L, unsigned int N, unsigned int seedBytes,
1562 PQGParams **pParams, PQGVerify **pVfy)
1563 {
1564 if (N == 0) {
1565 N = pqg_get_default_N(L);
1566 }
1567 if (seedBytes == 0) {
1568 /* seedBytes == L/8 for probable primes, N/8 for Shawe-Taylor Primes */
1569 seedBytes = N/8;
1570 }
1571 if (pqg_validate_dsa2(L,N) != SECSuccess) {
1572 /* error code already set */
1573 return SECFailure;
1574 }
1575 return pqg_ParamGen(L, N, FIPS186_3_ST_TYPE, seedBytes, pParams, pVfy);
1576 }
1577
1578
1579 /*
1580 * verify can use vfy structures returned from either FIPS186-1 or
1581 * FIPS186-2, and can handle differences in selected Hash functions to
1582 * generate the parameters.
1583 */
1584 SECStatus
1585 PQG_VerifyParams(const PQGParams *params,
1586 const PQGVerify *vfy, SECStatus *result)
1587 {
1588 SECStatus rv = SECSuccess;
1589 unsigned int g, n, L, N, offset, outlen;
1590 mp_int p0, P, Q, G, P_, Q_, G_, r, h;
1591 mp_err err = MP_OKAY;
1592 int j;
1593 unsigned int counter_max = 0; /* handle legacy L < 1024 */
1594 int qseed_len;
1595 SECItem pseed_ = {0, 0, 0};
1596 HASH_HashType hashtype;
1597 pqgGenType type;
1598
1599 #define CHECKPARAM(cond) \
1600 if (!(cond)) { \
1601 *result = SECFailure; \
1602 goto cleanup; \
1603 }
1604 if (!params || !vfy || !result) {
1605 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1606 return SECFailure;
1607 }
1608 /* always need at least p, q, and seed for any meaningful check */
1609 if ((params->prime.len == 0) || (params->subPrime.len == 0) ||
1610 (vfy->seed.len == 0)) {
1611 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1612 return SECFailure;
1613 }
1614 /* we want to either check PQ or G or both. If we don't have G, make
1615 * sure we have count so we can check P. */
1616 if ((params->base.len == 0) && (vfy->counter == -1)) {
1617 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1618 return SECFailure;
1619 }
1620
1621 MP_DIGITS(&p0) = 0;
1622 MP_DIGITS(&P) = 0;
1623 MP_DIGITS(&Q) = 0;
1624 MP_DIGITS(&G) = 0;
1625 MP_DIGITS(&P_) = 0;
1626 MP_DIGITS(&Q_) = 0;
1627 MP_DIGITS(&G_) = 0;
1628 MP_DIGITS(&r) = 0;
1629 MP_DIGITS(&h) = 0;
1630 CHECK_MPI_OK( mp_init(&p0) );
1631 CHECK_MPI_OK( mp_init(&P) );
1632 CHECK_MPI_OK( mp_init(&Q) );
1633 CHECK_MPI_OK( mp_init(&G) );
1634 CHECK_MPI_OK( mp_init(&P_) );
1635 CHECK_MPI_OK( mp_init(&Q_) );
1636 CHECK_MPI_OK( mp_init(&G_) );
1637 CHECK_MPI_OK( mp_init(&r) );
1638 CHECK_MPI_OK( mp_init(&h) );
1639 *result = SECSuccess;
1640 SECITEM_TO_MPINT(params->prime, &P);
1641 SECITEM_TO_MPINT(params->subPrime, &Q);
1642 /* if G isn't specified, just check P and Q */
1643 if (params->base.len != 0) {
1644 SECITEM_TO_MPINT(params->base, &G);
1645 }
1646 /* 1. Check (L,N) pair */
1647 N = mpl_significant_bits(&Q);
1648 L = mpl_significant_bits(&P);
1649 if (L < 1024) {
1650 /* handle DSA1 pqg parameters with less thatn 1024 bits*/
1651 CHECKPARAM( N == DSA1_Q_BITS );
1652 j = PQG_PBITS_TO_INDEX(L);
1653 CHECKPARAM( j >= 0 && j <= 8 );
1654 counter_max = 4096;
1655 } else {
1656 /* handle DSA2 parameters (includes DSA1, 1024 bits) */
1657 CHECKPARAM(pqg_validate_dsa2(L, N) == SECSuccess);
1658 counter_max = 4*L;
1659 }
1660 /* 3. G < P */
1661 if (params->base.len != 0) {
1662 CHECKPARAM( mp_cmp(&G, &P) < 0 );
1663 }
1664 /* 4. P % Q == 1 */
1665 CHECK_MPI_OK( mp_mod(&P, &Q, &r) );
1666 CHECKPARAM( mp_cmp_d(&r, 1) == 0 );
1667 /* 5. Q is prime */
1668 CHECKPARAM( mpp_pprime(&Q, prime_testcount_q(L,N)) == MP_YES );
1669 /* 6. P is prime */
1670 CHECKPARAM( mpp_pprime(&P, prime_testcount_p(L,N)) == MP_YES );
1671 /* Steps 7-12 are done only if the optional PQGVerify is supplied. */
1672 /* continue processing P */
1673 /* 7. counter < 4*L */
1674 CHECKPARAM( (vfy->counter == -1) || (vfy->counter < counter_max) );
1675 /* 8. g >= N and g < 2*L (g is length of seed in bits) */
1676 g = vfy->seed.len * 8;
1677 CHECKPARAM( g >= N && g < counter_max/2 );
1678 /* 9. Q generated from SEED matches Q in PQGParams. */
1679 /* This function checks all possible hash and generation types to
1680 * find a Q_ which matches Q. */
1681 CHECKPARAM( findQfromSeed(L, N, g, &vfy->seed, &Q, &Q_, &qseed_len,
1682 &hashtype, &type) == SECSuccess );
1683 CHECKPARAM( mp_cmp(&Q, &Q_) == 0 );
1684 if (type == FIPS186_3_ST_TYPE) {
1685 SECItem qseed = { 0, 0, 0 };
1686 SECItem pseed = { 0, 0, 0 };
1687 int first_seed_len;
1688 int pgen_counter = 0;
1689
1690 /* extract pseed and qseed from domain_parameter_seed, which is
1691 * first_seed || pseed || qseed. qseed is first_seed + small_integer
1692 * pseed is qseed + small_integer. This means most of the time
1693 * first_seed.len == qseed.len == pseed.len. Rarely qseed.len and/or
1694 * pseed.len will be one greater than first_seed.len, so we can
1695 * depend on the fact that
1696 * first_seed.len = floor(domain_parameter_seed.len/3).
1697 * findQfromSeed returned qseed.len, so we can calculate pseed.len as
1698 * pseed.len = domain_parameter_seed.len - first_seed.len - qseed.len
1699 * this is probably over kill, since 99.999% of the time they will all
1700 * be equal.
1701 *
1702 * With the lengths, we can now find the offsets;
1703 * first_seed.data = domain_parameter_seed.data + 0
1704 * pseed.data = domain_parameter_seed.data + first_seed.len
1705 * qseed.data = domain_parameter_seed.data
1706 * + domain_paramter_seed.len - qseed.len
1707 *
1708 */
1709 first_seed_len = vfy->seed.len/3;
1710 CHECKPARAM(qseed_len < vfy->seed.len);
1711 CHECKPARAM(first_seed_len*8 > N-1);
1712 CHECKPARAM(first_seed_len+qseed_len < vfy->seed.len);
1713 qseed.len = qseed_len;
1714 qseed.data = vfy->seed.data + vfy->seed.len - qseed.len;
1715 pseed.len = vfy->seed.len - (first_seed_len+qseed_len);
1716 pseed.data = vfy->seed.data + first_seed_len;
1717
1718 /*
1719 * now complete FIPS 186-3 A.1.2.1.2. Step 1 was completed
1720 * above in our initial checks, Step 2 was completed by
1721 * findQfromSeed */
1722
1723 /* Step 3 (status, c0, prime_seed, prime_gen_counter) =
1724 ** (ST_Random_Prime((ceil(length/2)+1, input_seed)
1725 */
1726 CHECK_SEC_OK( makePrimefromSeedShaweTaylor(hashtype, (L+1)/2+1,
1727 &qseed, &p0, &pseed_, &pgen_counter) );
1728 /* Steps 4-22 FIPS 186-3 appendix A.1.2.1.2 */
1729 CHECK_SEC_OK( makePrimefromPrimesShaweTaylor(hashtype, L,
1730 &p0, &Q_, &P_, &pseed_, &pgen_counter) );
1731 CHECKPARAM( mp_cmp(&P, &P_) == 0 );
1732 /* make sure pseed wasn't tampered with (since it is part of
1733 * calculating G) */
1734 CHECKPARAM( SECITEM_CompareItem(&pseed, &pseed_) == SECEqual );
1735 } else if (vfy->counter == -1) {
1736 /* If counter is set to -1, we are really only verifying G, skip
1737 * the remainder of the checks for P */
1738 CHECKPARAM(type != FIPS186_1_TYPE); /* we only do this for DSA2 */
1739 } else {
1740 /* 10. P generated from (L, counter, g, SEED, Q) matches P
1741 * in PQGParams. */
1742 outlen = HASH_ResultLen(hashtype)*BITS_PER_BYTE;
1743 n = (L - 1) / outlen;
1744 offset = vfy->counter * (n + 1) + ((type == FIPS186_1_TYPE) ? 2 : 1);
1745 CHECK_SEC_OK( makePfromQandSeed(hashtype, L, N, offset, g, &vfy->seed,
1746 &Q, &P_) );
1747 CHECKPARAM( mp_cmp(&P, &P_) == 0 );
1748 }
1749
1750 /* now check G, skip if don't have a g */
1751 if (params->base.len == 0) goto cleanup;
1752
1753 /* first Always check that G is OK FIPS186-3 A.2.2 & A.2.4*/
1754 /* 1. 2 < G < P-1 */
1755 /* P is prime, p-1 == zero 1st bit */
1756 CHECK_MPI_OK( mpl_set_bit(&P, 0, 0) );
1757 CHECKPARAM( mp_cmp_d(&G, 2) > 0 && mp_cmp(&G, &P) < 0 );
1758 CHECK_MPI_OK( mpl_set_bit(&P, 0, 1) ); /* set it back */
1759 /* 2. verify g**q mod p == 1 */
1760 CHECK_MPI_OK( mp_exptmod(&G, &Q, &P, &h) ); /* h = G ** Q mod P */
1761 CHECKPARAM(mp_cmp_d(&h, 1) == 0);
1762
1763 /* no h, the above is the best we can do */
1764 if (vfy->h.len == 0) {
1765 if (type != FIPS186_1_TYPE) {
1766 *result = SECWouldBlock;
1767 }
1768 goto cleanup;
1769 }
1770
1771 /*
1772 * If h is one byte and FIPS186-3 was used to generate Q (we've verified
1773 * Q was generated from seed already, then we assume that FIPS 186-3
1774 * appendix A.2.3 was used to generate G. Otherwise we assume A.2.1 was
1775 * used to generate G.
1776 */
1777 if ((vfy->h.len == 1) && (type != FIPS186_1_TYPE)) {
1778 /* A.2.3 */
1779 CHECK_SEC_OK(makeGfromIndex(hashtype, &P, &Q, &vfy->seed,
1780 vfy->h.data[0], &G_) );
1781 CHECKPARAM( mp_cmp(&G, &G_) == 0 );
1782 } else {
1783 int passed;
1784 /* A.2.1 */
1785 SECITEM_TO_MPINT(vfy->h, &h);
1786 /* 11. 1 < h < P-1 */
1787 /* P is prime, p-1 == zero 1st bit */
1788 CHECK_MPI_OK( mpl_set_bit(&P, 0, 0) );
1789 CHECKPARAM( mp_cmp_d(&G, 2) > 0 && mp_cmp(&G, &P) );
1790 CHECK_MPI_OK( mpl_set_bit(&P, 0, 1) ); /* set it back */
1791 /* 12. G generated from h matches G in PQGParams. */
1792 CHECK_SEC_OK( makeGfromH(&P, &Q, &h, &G_, &passed) );
1793 CHECKPARAM( passed && mp_cmp(&G, &G_) == 0 );
1794 }
1795 cleanup:
1796 mp_clear(&p0);
1797 mp_clear(&P);
1798 mp_clear(&Q);
1799 mp_clear(&G);
1800 mp_clear(&P_);
1801 mp_clear(&Q_);
1802 mp_clear(&G_);
1803 mp_clear(&r);
1804 mp_clear(&h);
1805 if (pseed_.data) {
1806 SECITEM_FreeItem(&pseed_,PR_FALSE);
1807 }
1808 if (err) {
1809 MP_TO_SEC_ERROR(err);
1810 rv = SECFailure;
1811 }
1812 return rv;
1813 }
1814
1815 /**************************************************************************
1816 * Free the PQGParams struct and the things it points to. *
1817 **************************************************************************/
1818 void
1819 PQG_DestroyParams(PQGParams *params)
1820 {
1821 if (params == NULL)
1822 return;
1823 if (params->arena != NULL) {
1824 PORT_FreeArena(params->arena, PR_FALSE); /* don't zero it */
1825 } else {
1826 SECITEM_FreeItem(&params->prime, PR_FALSE); /* don't free prime */
1827 SECITEM_FreeItem(&params->subPrime, PR_FALSE); /* don't free subPrime */
1828 SECITEM_FreeItem(&params->base, PR_FALSE); /* don't free base */
1829 PORT_Free(params);
1830 }
1831 }
1832
1833 /**************************************************************************
1834 * Free the PQGVerify struct and the things it points to. *
1835 **************************************************************************/
1836
1837 void
1838 PQG_DestroyVerify(PQGVerify *vfy)
1839 {
1840 if (vfy == NULL)
1841 return;
1842 if (vfy->arena != NULL) {
1843 PORT_FreeArena(vfy->arena, PR_FALSE); /* don't zero it */
1844 } else {
1845 SECITEM_FreeItem(&vfy->seed, PR_FALSE); /* don't free seed */
1846 SECITEM_FreeItem(&vfy->h, PR_FALSE); /* don't free h */
1847 PORT_Free(vfy);
1848 }
1849 }
OLDNEW
« no previous file with comments | « mozilla/security/nss/lib/freebl/pqg.h ('k') | mozilla/security/nss/lib/freebl/rawhash.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698