2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 * NB: these functions have been "upgraded", the deprecated versions (which
12 * are compatibility wrappers using these functions) are in rsa_depr.c. -
17 * RSA low level APIs are deprecated for public use, but still ok for
20 #include "internal/deprecated.h"
24 #include "internal/cryptlib.h"
25 #include <openssl/bn.h>
26 #include <openssl/self_test.h>
27 #include "prov/providercommon.h"
28 #include "rsa_local.h"
30 static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg);
31 static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
32 BIGNUM *e_value, BN_GENCB *cb, int pairwise_test);
35 * NB: this wrapper would normally be placed in rsa_lib.c and the static
36 * implementation would probably be in rsa_eay.c. Nonetheless, is kept here
37 * so that we don't introduce a new linker dependency. Eg. any application
38 * that wasn't previously linking object code related to key-generation won't
39 * have to now just because key-generation is part of RSA_METHOD.
41 int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
43 if (rsa->meth->rsa_keygen != NULL)
44 return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
46 return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM,
50 int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes,
51 BIGNUM *e_value, BN_GENCB *cb)
54 /* multi-prime is only supported with the builtin key generation */
55 if (rsa->meth->rsa_multi_prime_keygen != NULL) {
56 return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes,
58 } else if (rsa->meth->rsa_keygen != NULL) {
60 * However, if rsa->meth implements only rsa_keygen, then we
61 * have to honour it in 2-prime case and assume that it wouldn't
62 * know what to do with multi-prime key generated by builtin
66 return rsa->meth->rsa_keygen(rsa, bits, e_value, cb);
70 #endif /* FIPS_MODULE */
71 return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0);
75 static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes,
76 BIGNUM *e_value, BN_GENCB *cb)
78 BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime;
79 int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0;
80 int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0;
81 RSA_PRIME_INFO *pinfo = NULL;
82 STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL;
85 unsigned long error = 0;
88 if (bits < RSA_MIN_MODULUS_BITS) {
89 ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL);
92 if (e_value == NULL) {
93 ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE);
96 /* A bad value for e can cause infinite loops */
97 if (!ossl_rsa_check_public_exponent(e_value)) {
98 ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE);
102 if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) {
103 ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID);
107 ctx = BN_CTX_new_ex(rsa->libctx);
111 r0 = BN_CTX_get(ctx);
112 r1 = BN_CTX_get(ctx);
113 r2 = BN_CTX_get(ctx);
117 /* divide bits into 'primes' pieces evenly */
121 for (i = 0; i < primes; i++)
122 bitsr[i] = (i < rmd) ? quo + 1 : quo;
126 /* We need the RSA components non-NULL */
127 if (!rsa->n && ((rsa->n = BN_new()) == NULL))
129 if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL))
131 BN_set_flags(rsa->d, BN_FLG_CONSTTIME);
132 if (!rsa->e && ((rsa->e = BN_new()) == NULL))
134 if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL))
136 BN_set_flags(rsa->p, BN_FLG_CONSTTIME);
137 if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL))
139 BN_set_flags(rsa->q, BN_FLG_CONSTTIME);
140 if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL))
142 BN_set_flags(rsa->dmp1, BN_FLG_CONSTTIME);
143 if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL))
145 BN_set_flags(rsa->dmq1, BN_FLG_CONSTTIME);
146 if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL))
148 BN_set_flags(rsa->iqmp, BN_FLG_CONSTTIME);
150 /* initialize multi-prime components */
151 if (primes > RSA_DEFAULT_PRIME_NUM) {
152 rsa->version = RSA_ASN1_VERSION_MULTI;
153 prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2);
154 if (prime_infos == NULL)
156 if (rsa->prime_infos != NULL) {
157 /* could this happen? */
158 sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos,
159 ossl_rsa_multip_info_free);
161 rsa->prime_infos = prime_infos;
163 /* prime_info from 2 to |primes| -1 */
164 for (i = 2; i < primes; i++) {
165 pinfo = ossl_rsa_multip_info_new();
168 (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
172 if (BN_copy(rsa->e, e_value) == NULL)
175 /* generate p, q and other primes (if any) */
176 for (i = 0; i < primes; i++) {
185 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
188 BN_set_flags(prime, BN_FLG_CONSTTIME);
192 if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL,
196 * prime should not be equal to p, q, r_3...
197 * (those primes prior to this one)
202 for (j = 0; j < i; j++) {
210 prev_prime = sk_RSA_PRIME_INFO_value(prime_infos,
213 if (!BN_cmp(prime, prev_prime)) {
218 if (!BN_sub(r2, prime, BN_value_one()))
221 BN_set_flags(r2, BN_FLG_CONSTTIME);
222 if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) {
223 /* GCD == 1 since inverse exists */
226 error = ERR_peek_last_error();
227 if (ERR_GET_LIB(error) == ERR_LIB_BN
228 && ERR_GET_REASON(error) == BN_R_NO_INVERSE) {
234 if (!BN_GENCB_call(cb, 2, n++))
240 /* calculate n immediately to see if it's sufficient */
242 /* we get at least 2 primes */
243 if (!BN_mul(r1, rsa->p, rsa->q, ctx))
246 /* modulus n = p * q * r_3 * r_4 ... */
247 if (!BN_mul(r1, rsa->n, prime, ctx))
250 /* i == 0, do nothing */
251 if (!BN_GENCB_call(cb, 3, i))
256 * if |r1|, product of factors so far, is not as long as expected
257 * (by checking the first 4 bits are less than 0x9 or greater than
258 * 0xF). If so, re-generate the last prime.
260 * NOTE: This actually can't happen in two-prime case, because of
261 * the way factors are generated.
263 * Besides, another consideration is, for multi-prime case, even the
264 * length modulus is as long as expected, the modulus could start at
265 * 0x8, which could be utilized to distinguish a multi-prime private
266 * key by using the modulus in a certificate. This is also covered
267 * by checking the length should not be less than 0x9.
269 if (!BN_rshift(r2, r1, bitse - 4))
271 bitst = BN_get_word(r2);
273 if (bitst < 0x9 || bitst > 0xF) {
275 * For keys with more than 4 primes, we attempt longer factor to
276 * meet length requirement.
278 * Otherwise, we just re-generate the prime with the same length.
280 * This strategy has the following goals:
282 * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key
283 * 2. stay the same logic with normal 2-prime key
286 if (!BN_GENCB_call(cb, 2, n++))
293 } else if (retries == 4) {
295 * re-generate all primes from scratch, mainly used
296 * in 4 prime case to avoid long loop. Max retry times
306 /* save product of primes for further use, for multi-prime only */
307 if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL)
309 if (BN_copy(rsa->n, r1) == NULL)
311 if (!BN_GENCB_call(cb, 3, i))
315 if (BN_cmp(rsa->p, rsa->q) < 0) {
324 if (!BN_sub(r1, rsa->p, BN_value_one()))
327 if (!BN_sub(r2, rsa->q, BN_value_one()))
330 if (!BN_mul(r0, r1, r2, ctx))
333 for (i = 2; i < primes; i++) {
334 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
335 /* save r_i - 1 to pinfo->d temporarily */
336 if (!BN_sub(pinfo->d, pinfo->r, BN_value_one()))
338 if (!BN_mul(r0, r0, pinfo->d, ctx))
343 BIGNUM *pr0 = BN_new();
348 BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
349 if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
353 /* We MUST free pr0 before any further use of r0 */
358 BIGNUM *d = BN_new();
363 BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
365 /* calculate d mod (p-1) and d mod (q - 1) */
366 if (!BN_mod(rsa->dmp1, d, r1, ctx)
367 || !BN_mod(rsa->dmq1, d, r2, ctx)) {
372 /* calculate CRT exponents */
373 for (i = 2; i < primes; i++) {
374 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
375 /* pinfo->d == r_i - 1 */
376 if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) {
382 /* We MUST free d before any further use of rsa->d */
387 BIGNUM *p = BN_new();
391 BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
393 /* calculate inverse of q mod p */
394 if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
399 /* calculate CRT coefficient for other primes */
400 for (i = 2; i < primes; i++) {
401 pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2);
402 BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME);
403 if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) {
409 /* We MUST free p before any further use of rsa->p */
416 ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB);
423 #endif /* FIPS_MODULE */
425 static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes,
426 BIGNUM *e_value, BN_GENCB *cb, int pairwise_test)
431 ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
432 pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */
435 * Only multi-prime keys or insecure keys with a small key length or a
436 * public exponent <= 2^16 will use the older rsa_multiprime_keygen().
440 && (e_value == NULL || BN_num_bits(e_value) > 16))
441 ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb);
443 ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb);
444 #endif /* FIPS_MODULE */
446 if (pairwise_test && ok > 0) {
447 OSSL_CALLBACK *stcb = NULL;
448 void *stcbarg = NULL;
450 OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg);
451 ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg);
453 ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT);
454 /* Clear intermediate results */
455 BN_clear_free(rsa->d);
456 BN_clear_free(rsa->p);
457 BN_clear_free(rsa->q);
458 BN_clear_free(rsa->dmp1);
459 BN_clear_free(rsa->dmq1);
460 BN_clear_free(rsa->iqmp);
473 * For RSA key generation it is not known whether the key pair will be used
474 * for key transport or signatures. FIPS 140-2 IG 9.9 states that in this case
475 * either a signature verification OR an encryption operation may be used to
476 * perform the pairwise consistency check. The simpler encrypt/decrypt operation
477 * has been chosen for this case.
479 static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg)
482 unsigned int ciphertxt_len;
483 unsigned char *ciphertxt = NULL;
484 const unsigned char plaintxt[16] = {0};
485 unsigned char *decoded = NULL;
486 unsigned int decoded_len;
487 unsigned int plaintxt_len = (unsigned int)sizeof(plaintxt_len);
488 int padding = RSA_PKCS1_PADDING;
489 OSSL_SELF_TEST *st = NULL;
491 st = OSSL_SELF_TEST_new(cb, cbarg);
494 OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
495 OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1);
497 ciphertxt_len = RSA_size(rsa);
499 * RSA_private_encrypt() and RSA_private_decrypt() requires the 'to'
500 * parameter to be a maximum of RSA_size() - allocate space for both.
502 ciphertxt = OPENSSL_zalloc(ciphertxt_len * 2);
503 if (ciphertxt == NULL)
505 decoded = ciphertxt + ciphertxt_len;
507 ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa,
509 if (ciphertxt_len <= 0)
511 if (ciphertxt_len == plaintxt_len
512 && memcmp(ciphertxt, plaintxt, plaintxt_len) == 0)
515 OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt);
517 decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa,
519 if (decoded_len != plaintxt_len
520 || memcmp(decoded, plaintxt, decoded_len) != 0)
525 OSSL_SELF_TEST_onend(st, ret);
526 OSSL_SELF_TEST_free(st);
527 OPENSSL_free(ciphertxt);