renamed some IKEv2 OpenSSL scenarios
[strongswan.git] / src / scepclient / rsakey.c
1 /**
2 * @file rsakey.c
3 * @brief Functions for RSA key generation
4 */
5
6 /*
7 * Copyright (C) 1999, 2000, 2001 Henry Spencer.
8 * Copyright (C) 2005 Jan Hutter, Martin Willi
9 * Hochschule fuer Technik Rapperswil
10 *
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2 of the License, or (at your
14 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 * for more details.
20 */
21
22
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <assert.h>
29 #include <gmp.h>
30
31 #include <freeswan.h>
32
33 #include <library.h>
34 #include <crypto/rngs/rng.h>
35
36 #include "../pluto/constants.h"
37 #include "../pluto/defs.h"
38 #include "../pluto/mp_defs.h"
39 #include "../pluto/log.h"
40 #include "../pluto/pkcs1.h"
41
42 #include "rsakey.h"
43
44 /* Number of times the probabilistic primality test is applied */
45 #define PRIMECHECK_ROUNDS 30
46
47 /* Public exponent used for signature key generation */
48 #define PUBLIC_EXPONENT 0x10001
49
50 #ifndef DEV_RANDOM
51 #define DEV_RANDOM "/dev/random"
52 #endif
53
54
55 /**
56 * @brief Reads a specific number of bytes from a given device/file
57 *
58 * @param[in] nbytes number of bytes to read from random device
59 * @param[out] buf pointer to buffer where to write the data in.
60 * size of buffer has to be at least nbytes.
61 * @return TRUE, if succeeded, FALSE otherwise
62 */
63
64 /**
65 * @brief initialize an mpz_t to a random number, specified bit count
66 *
67 * Converting the random value in a value of type mpz_t is done
68 * by creating a hexbuffer.
69 * Converting via hex is a bit weird, but it's the best route GMP gives us.
70 * Note that highmost and lowmost bits are forced on -- highmost to give a
71 * number of exactly the specified length, lowmost so it is an odd number.
72 *
73 * @param[out] var uninitialized mpz_t to store th random number in
74 * @param[in] nbits length of var in bits (known to be a multiple of BITS_PER_BYTE)
75 * @return TRUE on success, FALSE otherwise
76 */
77 static bool init_random(mpz_t var, int nbits)
78 {
79 size_t nbytes = (size_t)(nbits/BITS_PER_BYTE);
80 char random_buf[RSA_MAX_OCTETS/2];
81 rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_TRUE);
82
83 if (!rng)
84 {
85 return FALSE;
86 }
87 assert(nbytes <= sizeof(random_buf));
88 rng->get_bytes(rng, nbytes, random_buf);
89 rng->destroy(rng);
90
91 random_buf[0] |= 01 << (BITS_PER_BYTE-1); /* force high bit on */
92 random_buf[nbytes-1] |= 01; /* force low bit on */
93 n_to_mpz(var, random_buf, nbytes);
94 return TRUE;
95 }
96
97 /**
98 * @brief initialize an mpz_t to a random prime of specified size
99 *
100 * Efficiency tweak: we reject candidates that are 1 higher than a multiple
101 * of e, since they will make the internal modulus not relatively prime to e.
102 *
103 * @param[out] var mpz_t variable to initialize
104 * @param[in] nbits length of given prime in bits (known to be a multiple of BITS_PER_BYTE)
105 * @param[in] eval E-Value, 0 means don't bother w. tweak
106 * @return 1 on success, 0 otherwise
107 */
108 static bool init_prime(mpz_t var, int nbits, int eval)
109 {
110 unsigned long tries;
111 size_t len;
112
113 /* get a random value of nbits length */
114 if (!init_random(var, nbits))
115 return FALSE;
116
117 /* check if odd number */
118 assert(mpz_fdiv_ui(var, 2) == 1);
119 DBG(DBG_CONTROLMORE,
120 DBG_log("looking for a prime starting there (can take a while)...")
121 )
122
123 tries = 1;
124 while (mpz_fdiv_ui(var, eval) == 1
125 || !mpz_probab_prime_p(var, PRIMECHECK_ROUNDS))
126 {
127 /* not a prime, increase by 2 */
128 mpz_add_ui(var, var, 2);
129 tries++;
130 }
131
132 len = mpz_sizeinbase(var, 2);
133
134 /* check bit length of primee */
135 assert(len == (size_t)nbits || len == (size_t)(nbits+1));
136
137 if (len == (size_t)(nbits+1))
138 {
139 DBG(DBG_CONTROLMORE,
140 DBG_log("carry out occurred (!), retrying...")
141 )
142 mpz_clear(var);
143 /* recursive call */
144 return init_prime(var, nbits, eval);
145 }
146 DBG(DBG_CONTROLMORE,
147 DBG_log("found it after %lu tries.",tries)
148 )
149 return TRUE;
150 }
151
152 /**
153 * @brief Generate a RSA key usable for encryption
154 *
155 * Generate an RSA key usable for encryption. All the
156 * values of the RSA key are filled into mpz_t parameters.
157 * These mpz_t parameters must not be initialized and have
158 * to be cleared with mpz_clear after using.
159 *
160 * @param[in] nbits size of rsa key in bits
161 * @return RSA_public_key_t containing the generated RSA key
162 */
163 err_t generate_rsa_private_key(int nbits, RSA_private_key_t *key)
164 {
165 mpz_t p, q, n, e, d, exp1, exp2, coeff;
166 mpz_t m, q1, t; /* temporary variables*/
167
168 DBG(DBG_CONTROL,
169 DBG_log("generating %d bit RSA key:", nbits)
170 )
171
172 if (nbits <= 0)
173 return "negative rsa key length!";
174
175 /* Get values of primes p and q */
176 DBG(DBG_CONTROLMORE,
177 DBG_log("initialize prime p")
178 )
179 if (!init_prime(p, nbits/2, PUBLIC_EXPONENT))
180 return "could not generate prime p";
181
182 DBG(DBG_CONTROLMORE,
183 DBG_log("initialize prime q")
184 )
185 if (!init_prime(q, nbits/2, PUBLIC_EXPONENT))
186 return "could not generate prime q";
187
188 mpz_init(t);
189
190 /* Swapping primes so p is larger then q */
191 if (mpz_cmp(p, q) < 0)
192 {
193 DBG(DBG_CONTROLMORE,
194 DBG_log("swapping primes so p is the larger...")
195 );
196 mpz_set(t, p);
197 mpz_set(p, q);
198 mpz_set(q, t);
199 }
200
201 DBG(DBG_CONTROLMORE,
202 DBG_log("computing modulus...")
203 )
204 mpz_init(n);
205 /* n = p*q */
206 mpz_mul(n, p, q);
207
208 /* Assign e the value of defined PUBLIC_EXPONENT */
209 mpz_init_set_ui(e, PUBLIC_EXPONENT);
210
211 DBG(DBG_CONTROLMORE,
212 DBG_log("computing lcm(p-1, q-1)...")
213 )
214 /* m = p */
215 mpz_init_set(m, p);
216 /* m = m-1 */
217 mpz_sub_ui(m, m, 1);
218 /* q1 = q */
219 mpz_init_set(q1, q);
220 /* q1 = q1-1 */
221 mpz_sub_ui(q1, q1, 1);
222 /* t = gcd(p-1, q-1) */
223 mpz_gcd(t, m, q1);
224 /* m = (p-1)*(q-1) */
225 mpz_mul(m, m, q1);
226 /* m = m / t */
227 mpz_divexact(m, m, t);
228 /* t = gcd(m, e) (greatest common divisor) */
229 mpz_gcd(t, m, e);
230 /* m and e relatively prime */
231 assert(mpz_cmp_ui(t, 1) == 0);
232
233 /* decryption key */
234 DBG(DBG_CONTROLMORE,
235 DBG_log("computing d...")
236 )
237 mpz_init(d);
238 /* e has an inverse mod m */
239 assert(mpz_invert(d, e, m));
240
241 /* make sure d is positive */
242 if (mpz_cmp_ui(d, 0) < 0)
243 mpz_add(d, d, m);
244
245 /* d has to be positive */
246 assert(mpz_cmp(d, m) < 0);
247
248 /* the speedup hacks */
249 DBG(DBG_CONTROLMORE,
250 DBG_log("computing exp1, exp1, coeff...")
251 )
252 mpz_init(exp1);
253 /* t = p-1 */
254 mpz_sub_ui(t, p, 1);
255 /* exp1 = d mod p-1 */
256 mpz_mod(exp1, d, t);
257
258 mpz_init(exp2);
259 /* t = q-1 */
260 mpz_sub_ui(t, q, 1);
261 /* exp2 = d mod q-1 */
262 mpz_mod(exp2, d, t);
263
264 mpz_init(coeff);
265 /* coeff = q^-1 mod p */
266 mpz_invert(coeff, q, p);
267
268 /* make sure coeff is positive */
269 if (mpz_cmp_ui(coeff, 0) < 0)
270 mpz_add(coeff, coeff, p);
271
272 /* coeff has to be positive */
273 assert(mpz_cmp(coeff, p) < 0);
274
275 /* Clear temporary variables */
276 mpz_clear(q1);
277 mpz_clear(m);
278 mpz_clear(t);
279
280 /* form FreeS/WAN keyid */
281 {
282 size_t e_len = (mpz_sizeinbase(e,2)+BITS_PER_BYTE-1)/BITS_PER_BYTE;
283 size_t n_len = (mpz_sizeinbase(n,2)+BITS_PER_BYTE-1)/BITS_PER_BYTE;
284 chunk_t e_ch = mpz_to_n(e, e_len);
285 chunk_t n_ch = mpz_to_n(n, n_len);
286
287 form_keyid(e_ch, n_ch, key->pub.keyid, &key->pub.k);
288 free(e_ch.ptr);
289 free(n_ch.ptr);
290 }
291
292 /* fill in the elements of the RSA private key */
293 key->p = *p;
294 key->q = *q;
295 key->pub.n = *n;
296 key->pub.e = *e;
297 key->d = *d;
298 key->dP = *exp1;
299 key->dQ = *exp2;
300 key->qInv = *coeff;
301
302 DBG(DBG_CONTROL,
303 DBG_log("RSA key *%s generated with %d bits", key->pub.keyid
304 , (int)mpz_sizeinbase(n,2))
305 )
306
307 #ifdef DEBUG
308 DBG(DBG_PRIVATE,
309 RSA_show_private_key(key)
310 )
311 #endif
312 return NULL;
313 }