3 * @brief Functions for RSA key generation
7 * Copyright (C) 1999, 2000, 2001 Henry Spencer.
8 * Copyright (C) 2005 Jan Hutter, Martin Willi
9 * Hochschule fuer Technik Rapperswil
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>.
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
24 #include <sys/types.h>
34 #include <crypto/rngs/rng.h>
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"
44 /* Number of times the probabilistic primality test is applied */
45 #define PRIMECHECK_ROUNDS 30
47 /* Public exponent used for signature key generation */
48 #define PUBLIC_EXPONENT 0x10001
51 #define DEV_RANDOM "/dev/random"
56 * @brief Reads a specific number of bytes from a given device/file
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
65 * @brief initialize an mpz_t to a random number, specified bit count
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.
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
77 static bool init_random(mpz_t var
, int nbits
)
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
);
87 assert(nbytes
<= sizeof(random_buf
));
88 rng
->get_bytes(rng
, nbytes
, random_buf
);
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
);
98 * @brief initialize an mpz_t to a random prime of specified size
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.
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
108 static bool init_prime(mpz_t var
, int nbits
, int eval
)
113 /* get a random value of nbits length */
114 if (!init_random(var
, nbits
))
117 /* check if odd number */
118 assert(mpz_fdiv_ui(var
, 2) == 1);
120 DBG_log("looking for a prime starting there (can take a while)...")
124 while (mpz_fdiv_ui(var
, eval
) == 1
125 || !mpz_probab_prime_p(var
, PRIMECHECK_ROUNDS
))
127 /* not a prime, increase by 2 */
128 mpz_add_ui(var
, var
, 2);
132 len
= mpz_sizeinbase(var
, 2);
134 /* check bit length of primee */
135 assert(len
== (size_t)nbits
|| len
== (size_t)(nbits
+1));
137 if (len
== (size_t)(nbits
+1))
140 DBG_log("carry out occurred (!), retrying...")
144 return init_prime(var
, nbits
, eval
);
147 DBG_log("found it after %lu tries.",tries
)
153 * @brief Generate a RSA key usable for encryption
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.
160 * @param[in] nbits size of rsa key in bits
161 * @return RSA_public_key_t containing the generated RSA key
163 err_t
generate_rsa_private_key(int nbits
, RSA_private_key_t
*key
)
165 mpz_t p
, q
, n
, e
, d
, exp1
, exp2
, coeff
;
166 mpz_t m
, q1
, t
; /* temporary variables*/
169 DBG_log("generating %d bit RSA key:", nbits
)
173 return "negative rsa key length!";
175 /* Get values of primes p and q */
177 DBG_log("initialize prime p")
179 if (!init_prime(p
, nbits
/2, PUBLIC_EXPONENT
))
180 return "could not generate prime p";
183 DBG_log("initialize prime q")
185 if (!init_prime(q
, nbits
/2, PUBLIC_EXPONENT
))
186 return "could not generate prime q";
190 /* Swapping primes so p is larger then q */
191 if (mpz_cmp(p
, q
) < 0)
194 DBG_log("swapping primes so p is the larger...")
202 DBG_log("computing modulus...")
208 /* Assign e the value of defined PUBLIC_EXPONENT */
209 mpz_init_set_ui(e
, PUBLIC_EXPONENT
);
212 DBG_log("computing lcm(p-1, q-1)...")
221 mpz_sub_ui(q1
, q1
, 1);
222 /* t = gcd(p-1, q-1) */
224 /* m = (p-1)*(q-1) */
227 mpz_divexact(m
, m
, t
);
228 /* t = gcd(m, e) (greatest common divisor) */
230 /* m and e relatively prime */
231 assert(mpz_cmp_ui(t
, 1) == 0);
235 DBG_log("computing d...")
238 /* e has an inverse mod m */
239 assert(mpz_invert(d
, e
, m
));
241 /* make sure d is positive */
242 if (mpz_cmp_ui(d
, 0) < 0)
245 /* d has to be positive */
246 assert(mpz_cmp(d
, m
) < 0);
248 /* the speedup hacks */
250 DBG_log("computing exp1, exp1, coeff...")
255 /* exp1 = d mod p-1 */
261 /* exp2 = d mod q-1 */
265 /* coeff = q^-1 mod p */
266 mpz_invert(coeff
, q
, p
);
268 /* make sure coeff is positive */
269 if (mpz_cmp_ui(coeff
, 0) < 0)
270 mpz_add(coeff
, coeff
, p
);
272 /* coeff has to be positive */
273 assert(mpz_cmp(coeff
, p
) < 0);
275 /* Clear temporary variables */
280 /* form FreeS/WAN keyid */
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
);
287 form_keyid(e_ch
, n_ch
, key
->pub
.keyid
, &key
->pub
.k
);
292 /* fill in the elements of the RSA private key */
303 DBG_log("RSA key *%s generated with %d bits", key
->pub
.keyid
304 , (int)mpz_sizeinbase(n
,2))
309 RSA_show_private_key(key
)