1 /* PRIME.C - primality-testing routines
4 /* Copyright (C) RSA Laboratories, a division of RSA Data Security,
5 Inc., created 1991. All rights reserved.
14 static unsigned int SMALL_PRIMES[] = { 3, 5, 7, 11 };
15 #define SMALL_PRIME_COUNT 4
17 static int ProbablePrime PROTO_LIST ((NN_DIGIT *, unsigned int));
18 static int SmallFactor PROTO_LIST ((NN_DIGIT *, unsigned int));
19 static int FermatTest PROTO_LIST ((NN_DIGIT *, unsigned int));
21 /* Generates a probable prime a between b and c such that a-1 is
24 Lengths: a[digits], b[digits], c[digits], d[digits].
25 Assumes b < c, digits < MAX_NN_DIGITS.
27 Returns RE_NEED_RANDOM if randomStruct not seeded, RE_DATA if
30 int GeneratePrime (a, b, c, d, digits, randomStruct)
31 NN_DIGIT *a, *b, *c, *d;
33 R_RANDOM_STRUCT *randomStruct;
36 unsigned char block[MAX_NN_DIGITS * NN_DIGIT_LEN];
37 NN_DIGIT t[MAX_NN_DIGITS], u[MAX_NN_DIGITS];
39 /* Generate random number between b and c.
41 if (status = R_GenerateBytes (block, digits * NN_DIGIT_LEN, randomStruct))
43 NN_Decode (a, digits, block, digits * NN_DIGIT_LEN);
44 NN_Sub (t, c, b, digits);
45 NN_ASSIGN_DIGIT (u, 1, digits);
46 NN_Add (t, t, u, digits);
47 NN_Mod (a, a, digits, t, digits);
48 NN_Add (a, a, b, digits);
50 /* Adjust so that a-1 is divisible by d.
52 NN_Mod (t, a, digits, d, digits);
53 NN_Sub (a, a, t, digits);
54 NN_Add (a, a, u, digits);
55 if (NN_Cmp (a, b, digits) < 0)
56 NN_Add (a, a, d, digits);
57 if (NN_Cmp (a, c, digits) > 0)
58 NN_Sub (a, a, d, digits);
60 /* Search to c in steps of d.
62 NN_Assign (t, c, digits);
63 NN_Sub (t, t, d, digits);
65 while (! ProbablePrime (a, digits)) {
66 if (NN_Cmp (a, t, digits) > 0)
68 NN_Add (a, a, d, digits);
74 /* Returns nonzero iff a is a probable prime.
77 Assumes aDigits < MAX_NN_DIGITS.
79 static int ProbablePrime (a, aDigits)
83 return (! SmallFactor (a, aDigits) && FermatTest (a, aDigits));
86 /* Returns nonzero iff a has a prime factor in SMALL_PRIMES.
89 Assumes aDigits < MAX_NN_DIGITS.
91 static int SmallFactor (a, aDigits)
101 for (i = 0; i < SMALL_PRIME_COUNT; i++) {
102 NN_ASSIGN_DIGIT (t, SMALL_PRIMES[i], 1);
103 if ((aDigits == 1) && ! NN_Cmp (a, t, 1))
105 NN_Mod (t, a, aDigits, t, 1);
106 if (NN_Zero (t, 1)) {
112 /* Zeroize sensitive information.
115 R_memset ((POINTER)t, 0, sizeof (t));
120 /* Returns nonzero iff a passes Fermat's test for witness 2.
121 (All primes pass the test, and nearly all composites fail.)
124 Assumes aDigits < MAX_NN_DIGITS.
126 static int FermatTest (a, aDigits)
128 unsigned int aDigits;
131 NN_DIGIT t[MAX_NN_DIGITS], u[MAX_NN_DIGITS];
133 NN_ASSIGN_DIGIT (t, 2, aDigits);
134 NN_ModExp (u, t, a, aDigits, a, aDigits);
136 status = NN_EQUAL (t, u, aDigits);
138 /* Zeroize sensitive information.
140 R_memset ((POINTER)u, 0, sizeof (u));