71e4b783061abeadd27675a264864337ac4bb236
[openssl.git] / crypto / rsa / rsa_lib.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9
10 #include <stdio.h>
11 #include <openssl/crypto.h>
12 #include <openssl/core_names.h>
13 #include <openssl/engine.h>
14 #include <openssl/evp.h>
15 #include "internal/cryptlib.h"
16 #include "internal/refcount.h"
17 #include "crypto/bn.h"
18 #include "crypto/evp.h"
19 #include "crypto/rsa.h"
20 #include "rsa_local.h"
21
22 RSA *RSA_new(void)
23 {
24     return RSA_new_method(NULL);
25 }
26
27 const RSA_METHOD *RSA_get_method(const RSA *rsa)
28 {
29     return rsa->meth;
30 }
31
32 int RSA_set_method(RSA *rsa, const RSA_METHOD *meth)
33 {
34     /*
35      * NB: The caller is specifically setting a method, so it's not up to us
36      * to deal with which ENGINE it comes from.
37      */
38     const RSA_METHOD *mtmp;
39     mtmp = rsa->meth;
40     if (mtmp->finish)
41         mtmp->finish(rsa);
42 #ifndef OPENSSL_NO_ENGINE
43     ENGINE_finish(rsa->engine);
44     rsa->engine = NULL;
45 #endif
46     rsa->meth = meth;
47     if (meth->init)
48         meth->init(rsa);
49     return 1;
50 }
51
52 RSA *RSA_new_method(ENGINE *engine)
53 {
54     RSA *ret = OPENSSL_zalloc(sizeof(*ret));
55
56     if (ret == NULL) {
57         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
58         return NULL;
59     }
60
61     ret->references = 1;
62     ret->lock = CRYPTO_THREAD_lock_new();
63     if (ret->lock == NULL) {
64         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
65         OPENSSL_free(ret);
66         return NULL;
67     }
68
69     ret->meth = RSA_get_default_method();
70 #ifndef OPENSSL_NO_ENGINE
71     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
72     if (engine) {
73         if (!ENGINE_init(engine)) {
74             RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
75             goto err;
76         }
77         ret->engine = engine;
78     } else {
79         ret->engine = ENGINE_get_default_RSA();
80     }
81     if (ret->engine) {
82         ret->meth = ENGINE_get_RSA(ret->engine);
83         if (ret->meth == NULL) {
84             RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
85             goto err;
86         }
87     }
88 #endif
89
90     ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
91     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_RSA, ret, &ret->ex_data)) {
92         goto err;
93     }
94
95     if ((ret->meth->init != NULL) && !ret->meth->init(ret)) {
96         RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_INIT_FAIL);
97         goto err;
98     }
99
100     return ret;
101
102  err:
103     RSA_free(ret);
104     return NULL;
105 }
106
107 void RSA_free(RSA *r)
108 {
109     int i;
110
111     if (r == NULL)
112         return;
113
114     CRYPTO_DOWN_REF(&r->references, &i, r->lock);
115     REF_PRINT_COUNT("RSA", r);
116     if (i > 0)
117         return;
118     REF_ASSERT_ISNT(i < 0);
119
120     if (r->meth != NULL && r->meth->finish != NULL)
121         r->meth->finish(r);
122 #ifndef OPENSSL_NO_ENGINE
123     ENGINE_finish(r->engine);
124 #endif
125
126     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RSA, r, &r->ex_data);
127
128     CRYPTO_THREAD_lock_free(r->lock);
129
130     BN_free(r->n);
131     BN_free(r->e);
132     BN_clear_free(r->d);
133     BN_clear_free(r->p);
134     BN_clear_free(r->q);
135     BN_clear_free(r->dmp1);
136     BN_clear_free(r->dmq1);
137     BN_clear_free(r->iqmp);
138     RSA_PSS_PARAMS_free(r->pss);
139     sk_RSA_PRIME_INFO_pop_free(r->prime_infos, rsa_multip_info_free);
140     BN_BLINDING_free(r->blinding);
141     BN_BLINDING_free(r->mt_blinding);
142     OPENSSL_free(r->bignum_data);
143     OPENSSL_free(r);
144 }
145
146 int RSA_up_ref(RSA *r)
147 {
148     int i;
149
150     if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0)
151         return 0;
152
153     REF_PRINT_COUNT("RSA", r);
154     REF_ASSERT_ISNT(i < 2);
155     return i > 1 ? 1 : 0;
156 }
157
158 int RSA_set_ex_data(RSA *r, int idx, void *arg)
159 {
160     return CRYPTO_set_ex_data(&r->ex_data, idx, arg);
161 }
162
163 void *RSA_get_ex_data(const RSA *r, int idx)
164 {
165     return CRYPTO_get_ex_data(&r->ex_data, idx);
166 }
167
168 /*
169  * Define a scaling constant for our fixed point arithmetic.
170  * This value must be a power of two because the base two logarithm code
171  * makes this assumption.  The exponent must also be a multiple of three so
172  * that the scale factor has an exact cube root.  Finally, the scale factor
173  * should not be so large that a multiplication of two scaled numbers
174  * overflows a 64 bit unsigned integer.
175  */
176 static const unsigned int scale = 1 << 18;
177 static const unsigned int cbrt_scale = 1 << (2 * 18 / 3);
178
179 /* Define some constants, none exceed 32 bits */
180 static const unsigned int log_2  = 0x02c5c8;    /* scale * log(2) */
181 static const unsigned int log_e  = 0x05c551;    /* scale * log2(M_E) */
182 static const unsigned int c1_923 = 0x07b126;    /* scale * 1.923 */
183 static const unsigned int c4_690 = 0x12c28f;    /* scale * 4.690 */
184
185 /*
186  * Multiply two scaled integers together and rescale the result.
187  */
188 static ossl_inline uint64_t mul2(uint64_t a, uint64_t b)
189 {
190     return a * b / scale;
191 }
192
193 /*
194  * Calculate the cube root of a 64 bit scaled integer.
195  * Although the cube root of a 64 bit number does fit into a 32 bit unsigned
196  * integer, this is not guaranteed after scaling, so this function has a
197  * 64 bit return.  This uses the shifting nth root algorithm with some
198  * algebraic simplifications.
199  */
200 static uint64_t icbrt64(uint64_t x)
201 {
202     uint64_t r = 0;
203     uint64_t b;
204     int s;
205
206     for (s = 63; s >= 0; s -= 3) {
207         r <<= 1;
208         b = 3 * r * (r + 1) + 1;
209         if ((x >> s) >= b) {
210             x -= b << s;
211             r++;
212         }
213     }
214     return r * cbrt_scale;
215 }
216
217 /*
218  * Calculate the natural logarithm of a 64 bit scaled integer.
219  * This is done by calculating a base two logarithm and scaling.
220  * The maximum logarithm (base 2) is 64 and this reduces base e, so
221  * a 32 bit result should not overflow.  The argument passed must be
222  * greater than unity so we don't need to handle negative results.
223  */
224 static uint32_t ilog_e(uint64_t v)
225 {
226     uint32_t i, r = 0;
227
228     /*
229      * Scale down the value into the range 1 .. 2.
230      *
231      * If fractional numbers need to be processed, another loop needs
232      * to go here that checks v < scale and if so multiplies it by 2 and
233      * reduces r by scale.  This also means making r signed.
234      */
235     while (v >= 2 * scale) {
236         v >>= 1;
237         r += scale;
238     }
239     for (i = scale / 2; i != 0; i /= 2) {
240         v = mul2(v, v);
241         if (v >= 2 * scale) {
242             v >>= 1;
243             r += i;
244         }
245     }
246     r = (r * (uint64_t)scale) / log_e;
247     return r;
248 }
249
250 /*
251  * NIST SP 800-56B rev 2 Appendix D: Maximum Security Strength Estimates for IFC
252  * Modulus Lengths.
253  *
254  * E = \frac{1.923 \sqrt[3]{nBits \cdot log_e(2)}
255  *           \cdot(log_e(nBits \cdot log_e(2))^{2/3} - 4.69}{log_e(2)}
256  * The two cube roots are merged together here.
257  */
258 uint16_t rsa_compute_security_bits(int n)
259 {
260     uint64_t x;
261     uint32_t lx;
262     uint16_t y;
263
264     /* Look for common values as listed in SP 800-56B rev 2 Appendix D */
265     switch (n) {
266     case 2048:
267         return 112;
268     case 3072:
269         return 128;
270     case 4096:
271         return 152;
272     case 6144:
273         return 176;
274     case 8192:
275         return 200;
276     }
277     /*
278      * The first incorrect result (i.e. not accurate or off by one low) occurs
279      * for n = 699668.  The true value here is 1200.  Instead of using this n
280      * as the check threshold, the smallest n such that the correct result is
281      * 1200 is used instead.
282      */
283     if (n >= 687737)
284         return 1200;
285     if (n < 8)
286         return 0;
287
288     x = n * (uint64_t)log_2;
289     lx = ilog_e(x);
290     y = (uint16_t)((mul2(c1_923, icbrt64(mul2(mul2(x, lx), lx))) - c4_690)
291                    / log_2);
292     return (y + 4) & ~7;
293 }
294
295 int RSA_security_bits(const RSA *rsa)
296 {
297     int bits = BN_num_bits(rsa->n);
298
299     if (rsa->version == RSA_ASN1_VERSION_MULTI) {
300         /* This ought to mean that we have private key at hand. */
301         int ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos);
302
303         if (ex_primes <= 0 || (ex_primes + 2) > rsa_multip_cap(bits))
304             return 0;
305     }
306     return rsa_compute_security_bits(bits);
307 }
308
309 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d)
310 {
311     /* If the fields n and e in r are NULL, the corresponding input
312      * parameters MUST be non-NULL for n and e.  d may be
313      * left NULL (in case only the public key is used).
314      */
315     if ((r->n == NULL && n == NULL)
316         || (r->e == NULL && e == NULL))
317         return 0;
318
319     if (n != NULL) {
320         BN_free(r->n);
321         r->n = n;
322     }
323     if (e != NULL) {
324         BN_free(r->e);
325         r->e = e;
326     }
327     if (d != NULL) {
328         BN_clear_free(r->d);
329         r->d = d;
330         BN_set_flags(r->d, BN_FLG_CONSTTIME);
331     }
332     r->dirty_cnt++;
333
334     return 1;
335 }
336
337 int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q)
338 {
339     /* If the fields p and q in r are NULL, the corresponding input
340      * parameters MUST be non-NULL.
341      */
342     if ((r->p == NULL && p == NULL)
343         || (r->q == NULL && q == NULL))
344         return 0;
345
346     if (p != NULL) {
347         BN_clear_free(r->p);
348         r->p = p;
349         BN_set_flags(r->p, BN_FLG_CONSTTIME);
350     }
351     if (q != NULL) {
352         BN_clear_free(r->q);
353         r->q = q;
354         BN_set_flags(r->q, BN_FLG_CONSTTIME);
355     }
356     r->dirty_cnt++;
357
358     return 1;
359 }
360
361 int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp)
362 {
363     /* If the fields dmp1, dmq1 and iqmp in r are NULL, the corresponding input
364      * parameters MUST be non-NULL.
365      */
366     if ((r->dmp1 == NULL && dmp1 == NULL)
367         || (r->dmq1 == NULL && dmq1 == NULL)
368         || (r->iqmp == NULL && iqmp == NULL))
369         return 0;
370
371     if (dmp1 != NULL) {
372         BN_clear_free(r->dmp1);
373         r->dmp1 = dmp1;
374         BN_set_flags(r->dmp1, BN_FLG_CONSTTIME);
375     }
376     if (dmq1 != NULL) {
377         BN_clear_free(r->dmq1);
378         r->dmq1 = dmq1;
379         BN_set_flags(r->dmq1, BN_FLG_CONSTTIME);
380     }
381     if (iqmp != NULL) {
382         BN_clear_free(r->iqmp);
383         r->iqmp = iqmp;
384         BN_set_flags(r->iqmp, BN_FLG_CONSTTIME);
385     }
386     r->dirty_cnt++;
387
388     return 1;
389 }
390
391 /*
392  * Is it better to export RSA_PRIME_INFO structure
393  * and related functions to let user pass a triplet?
394  */
395 int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[],
396                                 BIGNUM *coeffs[], int pnum)
397 {
398     STACK_OF(RSA_PRIME_INFO) *prime_infos, *old = NULL;
399     RSA_PRIME_INFO *pinfo;
400     int i;
401
402     if (primes == NULL || exps == NULL || coeffs == NULL || pnum == 0)
403         return 0;
404
405     prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum);
406     if (prime_infos == NULL)
407         return 0;
408
409     if (r->prime_infos != NULL)
410         old = r->prime_infos;
411
412     for (i = 0; i < pnum; i++) {
413         pinfo = rsa_multip_info_new();
414         if (pinfo == NULL)
415             goto err;
416         if (primes[i] != NULL && exps[i] != NULL && coeffs[i] != NULL) {
417             BN_clear_free(pinfo->r);
418             BN_clear_free(pinfo->d);
419             BN_clear_free(pinfo->t);
420             pinfo->r = primes[i];
421             pinfo->d = exps[i];
422             pinfo->t = coeffs[i];
423             BN_set_flags(pinfo->r, BN_FLG_CONSTTIME);
424             BN_set_flags(pinfo->d, BN_FLG_CONSTTIME);
425             BN_set_flags(pinfo->t, BN_FLG_CONSTTIME);
426         } else {
427             rsa_multip_info_free(pinfo);
428             goto err;
429         }
430         (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
431     }
432
433     r->prime_infos = prime_infos;
434
435     if (!rsa_multip_calc_product(r)) {
436         r->prime_infos = old;
437         goto err;
438     }
439
440     if (old != NULL) {
441         /*
442          * This is hard to deal with, since the old infos could
443          * also be set by this function and r, d, t should not
444          * be freed in that case. So currently, stay consistent
445          * with other *set0* functions: just free it...
446          */
447         sk_RSA_PRIME_INFO_pop_free(old, rsa_multip_info_free);
448     }
449
450     r->version = RSA_ASN1_VERSION_MULTI;
451     r->dirty_cnt++;
452
453     return 1;
454  err:
455     /* r, d, t should not be freed */
456     sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex);
457     return 0;
458 }
459
460 void RSA_get0_key(const RSA *r,
461                   const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
462 {
463     if (n != NULL)
464         *n = r->n;
465     if (e != NULL)
466         *e = r->e;
467     if (d != NULL)
468         *d = r->d;
469 }
470
471 void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q)
472 {
473     if (p != NULL)
474         *p = r->p;
475     if (q != NULL)
476         *q = r->q;
477 }
478
479 int RSA_get_multi_prime_extra_count(const RSA *r)
480 {
481     int pnum;
482
483     pnum = sk_RSA_PRIME_INFO_num(r->prime_infos);
484     if (pnum <= 0)
485         pnum = 0;
486     return pnum;
487 }
488
489 int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[])
490 {
491     int pnum, i;
492     RSA_PRIME_INFO *pinfo;
493
494     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
495         return 0;
496
497     /*
498      * return other primes
499      * it's caller's responsibility to allocate oth_primes[pnum]
500      */
501     for (i = 0; i < pnum; i++) {
502         pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
503         primes[i] = pinfo->r;
504     }
505
506     return 1;
507 }
508
509 void RSA_get0_crt_params(const RSA *r,
510                          const BIGNUM **dmp1, const BIGNUM **dmq1,
511                          const BIGNUM **iqmp)
512 {
513     if (dmp1 != NULL)
514         *dmp1 = r->dmp1;
515     if (dmq1 != NULL)
516         *dmq1 = r->dmq1;
517     if (iqmp != NULL)
518         *iqmp = r->iqmp;
519 }
520
521 int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[],
522                                     const BIGNUM *coeffs[])
523 {
524     int pnum;
525
526     if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0)
527         return 0;
528
529     /* return other primes */
530     if (exps != NULL || coeffs != NULL) {
531         RSA_PRIME_INFO *pinfo;
532         int i;
533
534         /* it's the user's job to guarantee the buffer length */
535         for (i = 0; i < pnum; i++) {
536             pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
537             if (exps != NULL)
538                 exps[i] = pinfo->d;
539             if (coeffs != NULL)
540                 coeffs[i] = pinfo->t;
541         }
542     }
543
544     return 1;
545 }
546
547 const BIGNUM *RSA_get0_n(const RSA *r)
548 {
549     return r->n;
550 }
551
552 const BIGNUM *RSA_get0_e(const RSA *r)
553 {
554     return r->e;
555 }
556
557 const BIGNUM *RSA_get0_d(const RSA *r)
558 {
559     return r->d;
560 }
561
562 const BIGNUM *RSA_get0_p(const RSA *r)
563 {
564     return r->p;
565 }
566
567 const BIGNUM *RSA_get0_q(const RSA *r)
568 {
569     return r->q;
570 }
571
572 const BIGNUM *RSA_get0_dmp1(const RSA *r)
573 {
574     return r->dmp1;
575 }
576
577 const BIGNUM *RSA_get0_dmq1(const RSA *r)
578 {
579     return r->dmq1;
580 }
581
582 const BIGNUM *RSA_get0_iqmp(const RSA *r)
583 {
584     return r->iqmp;
585 }
586
587 void RSA_clear_flags(RSA *r, int flags)
588 {
589     r->flags &= ~flags;
590 }
591
592 int RSA_test_flags(const RSA *r, int flags)
593 {
594     return r->flags & flags;
595 }
596
597 void RSA_set_flags(RSA *r, int flags)
598 {
599     r->flags |= flags;
600 }
601
602 int RSA_get_version(RSA *r)
603 {
604     /* { two-prime(0), multi(1) } */
605     return r->version;
606 }
607
608 ENGINE *RSA_get0_engine(const RSA *r)
609 {
610     return r->engine;
611 }
612
613 int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2)
614 {
615     /* If key type not RSA or RSA-PSS return error */
616     if (ctx != NULL && ctx->pmeth != NULL
617         && ctx->pmeth->pkey_id != EVP_PKEY_RSA
618         && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
619         return -1;
620      return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, p1, p2);
621 }
622
623 DEFINE_STACK_OF(BIGNUM)
624
625 int rsa_set0_all_params(RSA *r, const STACK_OF(BIGNUM) *primes,
626                         const STACK_OF(BIGNUM) *exps,
627                         const STACK_OF(BIGNUM) *coeffs)
628 {
629     STACK_OF(RSA_PRIME_INFO) *prime_infos, *old_infos = NULL;
630     int pnum;
631
632     if (primes == NULL || exps == NULL || coeffs == NULL)
633         return 0;
634
635     pnum = sk_BIGNUM_num(primes);
636     if (pnum < 2
637         || pnum != sk_BIGNUM_num(exps)
638         || pnum != sk_BIGNUM_num(coeffs) + 1)
639         return 0;
640
641     if (!RSA_set0_factors(r, sk_BIGNUM_value(primes, 0),
642                           sk_BIGNUM_value(primes, 1))
643         || !RSA_set0_crt_params(r, sk_BIGNUM_value(exps, 0),
644                                 sk_BIGNUM_value(exps, 1),
645                                 sk_BIGNUM_value(coeffs, 0)))
646         return 0;
647
648     old_infos = r->prime_infos;
649
650     if (pnum > 2) {
651         int i;
652
653         prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum);
654         if (prime_infos == NULL)
655             return 0;
656
657         for (i = 2; i < pnum; i++) {
658             BIGNUM *prime = sk_BIGNUM_value(primes, i);
659             BIGNUM *exp = sk_BIGNUM_value(exps, i);
660             BIGNUM *coeff = sk_BIGNUM_value(coeffs, i - 1);
661             RSA_PRIME_INFO *pinfo = NULL;
662
663             if (!ossl_assert(prime != NULL && exp != NULL && coeff != NULL))
664                 goto err;
665
666             /* Using rsa_multip_info_new() is wasteful, so allocate directly */
667             if ((pinfo = OPENSSL_zalloc(sizeof(*pinfo))) == NULL) {
668                 ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
669                 goto err;
670             }
671
672             pinfo->r = prime;
673             pinfo->d = exp;
674             pinfo->t = coeff;
675             BN_set_flags(pinfo->r, BN_FLG_CONSTTIME);
676             BN_set_flags(pinfo->d, BN_FLG_CONSTTIME);
677             BN_set_flags(pinfo->t, BN_FLG_CONSTTIME);
678             (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo);
679         }
680
681         r->prime_infos = prime_infos;
682
683         if (!rsa_multip_calc_product(r)) {
684             r->prime_infos = old_infos;
685             goto err;
686         }
687     }
688
689     if (old_infos != NULL) {
690         /*
691          * This is hard to deal with, since the old infos could
692          * also be set by this function and r, d, t should not
693          * be freed in that case. So currently, stay consistent
694          * with other *set0* functions: just free it...
695          */
696         sk_RSA_PRIME_INFO_pop_free(old_infos, rsa_multip_info_free);
697     }
698
699     r->version = pnum > 2 ? RSA_ASN1_VERSION_MULTI : RSA_ASN1_VERSION_DEFAULT;
700     r->dirty_cnt++;
701
702     return 1;
703  err:
704     /* r, d, t should not be freed */
705     sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex);
706     return 0;
707 }
708
709 DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM)
710
711 int rsa_get0_all_params(RSA *r, STACK_OF(BIGNUM_const) *primes,
712                         STACK_OF(BIGNUM_const) *exps,
713                         STACK_OF(BIGNUM_const) *coeffs)
714 {
715     RSA_PRIME_INFO *pinfo;
716     int i, pnum;
717
718     if (r == NULL)
719         return 0;
720
721     pnum = RSA_get_multi_prime_extra_count(r);
722
723     sk_BIGNUM_const_push(primes, RSA_get0_p(r));
724     sk_BIGNUM_const_push(primes, RSA_get0_q(r));
725     sk_BIGNUM_const_push(exps, RSA_get0_dmp1(r));
726     sk_BIGNUM_const_push(exps, RSA_get0_dmq1(r));
727     sk_BIGNUM_const_push(coeffs, RSA_get0_iqmp(r));
728     for (i = 0; i < pnum; i++) {
729         pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i);
730         sk_BIGNUM_const_push(primes, pinfo->r);
731         sk_BIGNUM_const_push(exps, pinfo->d);
732         sk_BIGNUM_const_push(coeffs, pinfo->t);
733     }
734
735     return 1;
736 }
737
738 int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int pad_mode)
739 {
740     OSSL_PARAM pad_params[2], *p = pad_params;
741
742     if (ctx == NULL) {
743         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
744         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
745         return -2;
746     }
747
748     /* If key type not RSA or RSA-PSS return error */
749     if (ctx->pmeth != NULL
750             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
751             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
752         return -1;
753
754     /* TODO(3.0): Remove this eventually when no more legacy */
755     if (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
756             || ctx->op.ciph.ciphprovctx == NULL)
757         return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_RSA_PADDING,
758                                  pad_mode, NULL);
759
760     *p++ = OSSL_PARAM_construct_int(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, &pad_mode);
761     *p++ = OSSL_PARAM_construct_end();
762
763     return EVP_PKEY_CTX_set_params(ctx, pad_params);
764 }
765
766 int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *pad_mode)
767 {
768     OSSL_PARAM pad_params[2], *p = pad_params;
769
770     if (ctx == NULL || pad_mode == NULL) {
771         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
772         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
773         return -2;
774     }
775
776     /* If key type not RSA or RSA-PSS return error */
777     if (ctx->pmeth != NULL
778             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
779             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
780         return -1;
781
782     /* TODO(3.0): Remove this eventually when no more legacy */
783     if (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
784             || ctx->op.ciph.ciphprovctx == NULL)
785         return EVP_PKEY_CTX_ctrl(ctx, -1, -1, EVP_PKEY_CTRL_GET_RSA_PADDING, 0,
786                                  pad_mode);
787
788     *p++ = OSSL_PARAM_construct_int(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, pad_mode);
789     *p++ = OSSL_PARAM_construct_end();
790
791     if (!EVP_PKEY_CTX_get_params(ctx, pad_params))
792         return 0;
793
794     return 1;
795
796 }
797
798 int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
799 {
800     const char *name;
801
802     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
803         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
804         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
805         return -2;
806     }
807
808     /* If key type not RSA return error */
809     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
810         return -1;
811
812     /* TODO(3.0): Remove this eventually when no more legacy */
813     if (ctx->op.ciph.ciphprovctx == NULL)
814         return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
815                                  EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)md);
816
817     name = (md == NULL) ? "" : EVP_MD_name(md);
818
819     return EVP_PKEY_CTX_set_rsa_oaep_md_name(ctx, name, NULL);
820 }
821
822 int EVP_PKEY_CTX_set_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
823                                       const char *mdprops)
824 {
825     OSSL_PARAM rsa_params[3], *p = rsa_params;
826
827     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
828         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
829         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
830         return -2;
831     }
832
833     /* If key type not RSA return error */
834     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
835         return -1;
836
837
838     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
839                                             /*
840                                              * Cast away the const. This is read
841                                              * only so should be safe
842                                              */
843                                             (char *)mdname,
844                                             strlen(mdname) + 1);
845     if (mdprops != NULL) {
846         *p++ = OSSL_PARAM_construct_utf8_string(
847                     OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS,
848                     /*
849                      * Cast away the const. This is read
850                      * only so should be safe
851                      */
852                     (char *)mdprops,
853                     strlen(mdprops) + 1);
854     }
855     *p++ = OSSL_PARAM_construct_end();
856
857     return EVP_PKEY_CTX_set_params(ctx, rsa_params);
858 }
859
860 int EVP_PKEY_CTX_get_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, char *name,
861                                       size_t namelen)
862 {
863     OSSL_PARAM rsa_params[2], *p = rsa_params;
864
865     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
866         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
867         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
868         return -2;
869     }
870
871     /* If key type not RSA return error */
872     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
873         return -1;
874
875     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
876                                             name, namelen);
877     *p++ = OSSL_PARAM_construct_end();
878
879     if (!EVP_PKEY_CTX_get_params(ctx, rsa_params))
880         return -1;
881
882     return 1;
883 }
884
885 int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **md)
886 {
887     /* 80 should be big enough */
888     char name[80] = "";
889
890     if (ctx == NULL || md == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
891         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
892         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
893         return -2;
894     }
895
896     /* If key type not RSA return error */
897     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
898         return -1;
899
900     /* TODO(3.0): Remove this eventually when no more legacy */
901     if (ctx->op.ciph.ciphprovctx == NULL)
902         return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
903                                  EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)md);
904
905     if (EVP_PKEY_CTX_get_rsa_oaep_md_name(ctx, name, sizeof(name)) <= 0)
906         return -1;
907
908     /* May be NULL meaning "unknown" */
909     *md = EVP_get_digestbyname(name);
910
911     return 1;
912 }
913
914 int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md)
915 {
916     const char *name;
917
918     if (ctx == NULL
919             || (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
920                 && !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx))) {
921         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
922         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
923         return -2;
924     }
925
926     /* If key type not RSA return error */
927     if (ctx->pmeth != NULL
928             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
929             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
930         return -1;
931
932     /* TODO(3.0): Remove this eventually when no more legacy */
933     if ((EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
934                 && ctx->op.ciph.ciphprovctx == NULL)
935             || (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
936                 && ctx->op.sig.sigprovctx == NULL))
937         return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA,
938                                  EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT,
939                                  EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)md);
940
941     name = (md == NULL) ? "" : EVP_MD_name(md);
942
943     return EVP_PKEY_CTX_set_rsa_mgf1_md_name(ctx, name, NULL);
944 }
945
946 int EVP_PKEY_CTX_set_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
947                                       const char *mdprops)
948 {
949     OSSL_PARAM rsa_params[3], *p = rsa_params;
950
951     if (ctx == NULL
952             || mdname == NULL
953             || (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
954                 && !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx))) {
955         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
956         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
957         return -2;
958     }
959
960     /* If key type not RSA return error */
961     if (ctx->pmeth != NULL
962             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
963             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
964         return -1;
965
966     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST,
967                                             /*
968                                              * Cast away the const. This is read
969                                              * only so should be safe
970                                              */
971                                             (char *)mdname,
972                                             strlen(mdname) + 1);
973     if (mdprops != NULL) {
974         *p++ = OSSL_PARAM_construct_utf8_string(
975                     OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS,
976                     /*
977                      * Cast away the const. This is read
978                      * only so should be safe
979                      */
980                     (char *)mdprops,
981                     strlen(mdprops) + 1);
982     }
983     *p++ = OSSL_PARAM_construct_end();
984
985     return EVP_PKEY_CTX_set_params(ctx, rsa_params);
986 }
987
988 int EVP_PKEY_CTX_get_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, char *name,
989                                       size_t namelen)
990 {
991     OSSL_PARAM rsa_params[2], *p = rsa_params;
992
993     if (ctx == NULL
994             || (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
995                 && !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx))) {
996         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
997         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
998         return -2;
999     }
1000
1001     /* If key type not RSA or RSA-PSS return error */
1002     if (ctx->pmeth != NULL
1003             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
1004             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
1005         return -1;
1006
1007     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST,
1008                                             name, namelen);
1009     *p++ = OSSL_PARAM_construct_end();
1010
1011     if (!EVP_PKEY_CTX_get_params(ctx, rsa_params))
1012         return -1;
1013
1014     return 1;
1015 }
1016
1017 int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **md)
1018 {
1019     /* 80 should be big enough */
1020     char name[80] = "";
1021
1022     if (ctx == NULL
1023             || (!EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
1024                 && !EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx))) {
1025         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1026         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1027         return -2;
1028     }
1029
1030     /* If key type not RSA or RSA-PSS return error */
1031     if (ctx->pmeth != NULL
1032             && ctx->pmeth->pkey_id != EVP_PKEY_RSA
1033             && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS)
1034         return -1;
1035
1036     /* TODO(3.0): Remove this eventually when no more legacy */
1037     if ((EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)
1038                 && ctx->op.ciph.ciphprovctx == NULL)
1039             || (EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx)
1040                 && ctx->op.sig.sigprovctx == NULL))
1041         return EVP_PKEY_CTX_ctrl(ctx, -1,
1042                                  EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT,
1043                                  EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)md);
1044
1045     if (EVP_PKEY_CTX_get_rsa_mgf1_md_name(ctx, name, sizeof(name)) <= 0)
1046         return -1;
1047
1048     /* May be NULL meaning "unknown" */
1049     *md = EVP_get_digestbyname(name);
1050
1051     return 1;
1052 }
1053
1054 int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, void *label, int llen)
1055 {
1056     OSSL_PARAM rsa_params[2], *p = rsa_params;
1057
1058     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
1059         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1060         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1061         return -2;
1062     }
1063
1064     /* If key type not RSA return error */
1065     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
1066         return -1;
1067
1068     /* TODO(3.0): Remove this eventually when no more legacy */
1069     if (ctx->op.ciph.ciphprovctx == NULL)
1070         return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
1071                                  EVP_PKEY_CTRL_RSA_OAEP_LABEL, llen,
1072                                  (void *)label);
1073
1074     *p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,
1075                                             /*
1076                                              * Cast away the const. This is read
1077                                              * only so should be safe
1078                                              */
1079                                             (void *)label,
1080                                             (size_t)llen);
1081     *p++ = OSSL_PARAM_construct_end();
1082
1083     if (!EVP_PKEY_CTX_set_params(ctx, rsa_params))
1084         return 0;
1085
1086     OPENSSL_free(label);
1087     return 1;
1088 }
1089
1090 int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, unsigned char **label)
1091 {
1092     OSSL_PARAM rsa_params[3], *p = rsa_params;
1093     size_t labellen;
1094
1095     if (ctx == NULL || !EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx)) {
1096         ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED);
1097         /* Uses the same return values as EVP_PKEY_CTX_ctrl */
1098         return -2;
1099     }
1100
1101     /* If key type not RSA return error */
1102     if (ctx->pmeth != NULL && ctx->pmeth->pkey_id != EVP_PKEY_RSA)
1103         return -1;
1104
1105     /* TODO(3.0): Remove this eventually when no more legacy */
1106     if (ctx->op.ciph.ciphprovctx == NULL)
1107         return EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT,
1108                                  EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, 0,
1109                                  (void *)label);
1110
1111     *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,
1112                                           (void **)label, 0);
1113     *p++ = OSSL_PARAM_construct_size_t(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL_LEN,
1114                                        &labellen);
1115     *p++ = OSSL_PARAM_construct_end();
1116
1117     if (!EVP_PKEY_CTX_get_params(ctx, rsa_params))
1118         return -1;
1119
1120     if (labellen > INT_MAX)
1121         return -1;
1122
1123     return (int)labellen;
1124 }