xref: /optee_os/lib/libmbedtls/mbedtls/library/rsa.c (revision 6cfa381e534b362afbd103f526b132048e54ba47)
1 /*
2  *  The RSA public-key cryptosystem
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 /*
21  *  The following sources were referenced in the design of this implementation
22  *  of the RSA algorithm:
23  *
24  *  [1] A method for obtaining digital signatures and public-key cryptosystems
25  *      R Rivest, A Shamir, and L Adleman
26  *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
27  *
28  *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
29  *      Menezes, van Oorschot and Vanstone
30  *
31  *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
32  *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
33  *      Stefan Mangard
34  *      https://arxiv.org/abs/1702.08719v2
35  *
36  */
37 
38 #include "common.h"
39 
40 #if defined(MBEDTLS_RSA_C)
41 
42 #include "mbedtls/rsa.h"
43 #include "rsa_alt_helpers.h"
44 #include "mbedtls/oid.h"
45 #include "mbedtls/platform_util.h"
46 #include "mbedtls/error.h"
47 #include "constant_time_internal.h"
48 #include "mbedtls/constant_time.h"
49 #include "hash_info.h"
50 
51 #include <string.h>
52 
53 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
54 #include <stdlib.h>
55 #endif
56 
57 /* We use MD first if it's available (for compatibility reasons)
58  * and "fall back" to PSA otherwise (which needs psa_crypto_init()). */
59 #if defined(MBEDTLS_PKCS1_V21)
60 #if !defined(MBEDTLS_MD_C)
61 #include "psa/crypto.h"
62 #include "mbedtls/psa_util.h"
63 #define PSA_TO_MBEDTLS_ERR(status) PSA_TO_MBEDTLS_ERR_LIST(status,   \
64                                                            psa_to_md_errors,              \
65                                                            psa_generic_status_to_mbedtls)
66 #endif /* !MBEDTLS_MD_C */
67 #endif /* MBEDTLS_PKCS1_V21 */
68 
69 #include "mbedtls/platform.h"
70 
71 #include <fault_mitigation.h>
72 
73 #if !defined(MBEDTLS_RSA_ALT)
74 
75 int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
76                        const mbedtls_mpi *N,
77                        const mbedtls_mpi *P, const mbedtls_mpi *Q,
78                        const mbedtls_mpi *D, const mbedtls_mpi *E)
79 {
80     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
81 
82     if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
83         (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
84         (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
85         (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
86         (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
87         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
88     }
89 
90     if (N != NULL) {
91         ctx->len = mbedtls_mpi_size(&ctx->N);
92     }
93 
94     return 0;
95 }
96 
97 int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
98                            unsigned char const *N, size_t N_len,
99                            unsigned char const *P, size_t P_len,
100                            unsigned char const *Q, size_t Q_len,
101                            unsigned char const *D, size_t D_len,
102                            unsigned char const *E, size_t E_len)
103 {
104     int ret = 0;
105 
106     if (N != NULL) {
107         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
108         ctx->len = mbedtls_mpi_size(&ctx->N);
109     }
110 
111     if (P != NULL) {
112         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
113     }
114 
115     if (Q != NULL) {
116         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
117     }
118 
119     if (D != NULL) {
120         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
121     }
122 
123     if (E != NULL) {
124         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
125     }
126 
127 cleanup:
128 
129     if (ret != 0) {
130         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
131     }
132 
133     return 0;
134 }
135 
136 /*
137  * Checks whether the context fields are set in such a way
138  * that the RSA primitives will be able to execute without error.
139  * It does *not* make guarantees for consistency of the parameters.
140  */
141 static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
142                              int blinding_needed)
143 {
144 #if !defined(MBEDTLS_RSA_NO_CRT)
145     /* blinding_needed is only used for NO_CRT to decide whether
146      * P,Q need to be present or not. */
147     ((void) blinding_needed);
148 #endif
149 
150     if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
151         ctx->len > MBEDTLS_MPI_MAX_SIZE) {
152         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
153     }
154 
155     /*
156      * 1. Modular exponentiation needs positive, odd moduli.
157      */
158 
159     /* Modular exponentiation wrt. N is always used for
160      * RSA public key operations. */
161     if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
162         mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
163         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
164     }
165 
166 #if !defined(MBEDTLS_RSA_NO_CRT)
167     /* Modular exponentiation for P and Q is only
168      * used for private key operations and if CRT
169      * is used. */
170     if (is_priv &&
171         (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
172          mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
173          mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
174          mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
175         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
176     }
177 #endif /* !MBEDTLS_RSA_NO_CRT */
178 
179     /*
180      * 2. Exponents must be positive
181      */
182 
183     /* Always need E for public key operations */
184     if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
185         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
186     }
187 
188 #if defined(MBEDTLS_RSA_NO_CRT)
189     /* For private key operations, use D or DP & DQ
190      * as (unblinded) exponents. */
191     if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
192         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
193     }
194 #else
195     if (is_priv &&
196         (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
197          mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
198         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
199     }
200 #endif /* MBEDTLS_RSA_NO_CRT */
201 
202     /* Blinding shouldn't make exponents negative either,
203      * so check that P, Q >= 1 if that hasn't yet been
204      * done as part of 1. */
205 #if defined(MBEDTLS_RSA_NO_CRT)
206     if (is_priv && blinding_needed &&
207         (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
208          mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
209         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
210     }
211 #endif
212 
213     /* It wouldn't lead to an error if it wasn't satisfied,
214      * but check for QP >= 1 nonetheless. */
215 #if !defined(MBEDTLS_RSA_NO_CRT)
216     if (is_priv &&
217         mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
218         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
219     }
220 #endif
221 
222     return 0;
223 }
224 
225 int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
226 {
227     int ret = 0;
228     int have_N, have_P, have_Q, have_D, have_E;
229 #if !defined(MBEDTLS_RSA_NO_CRT)
230     int have_DP, have_DQ, have_QP;
231 #endif
232     int n_missing, pq_missing, d_missing, is_pub, is_priv;
233 
234     have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
235     have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
236     have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
237     have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
238     have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
239 
240 #if !defined(MBEDTLS_RSA_NO_CRT)
241     have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
242     have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
243     have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
244 #endif
245 
246     /*
247      * Check whether provided parameters are enough
248      * to deduce all others. The following incomplete
249      * parameter sets for private keys are supported:
250      *
251      * (1) P, Q missing.
252      * (2) D and potentially N missing.
253      *
254      */
255 
256     n_missing  =              have_P &&  have_Q &&  have_D && have_E;
257     pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
258     d_missing  =              have_P &&  have_Q && !have_D && have_E;
259     is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
260 
261     /* These three alternatives are mutually exclusive */
262     is_priv = n_missing || pq_missing || d_missing;
263 
264     if (!is_priv && !is_pub) {
265         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
266     }
267 
268     /*
269      * Step 1: Deduce N if P, Q are provided.
270      */
271 
272     if (!have_N && have_P && have_Q) {
273         if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
274                                        &ctx->Q)) != 0) {
275             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
276         }
277 
278         ctx->len = mbedtls_mpi_size(&ctx->N);
279     }
280 
281     /*
282      * Step 2: Deduce and verify all remaining core parameters.
283      */
284 
285     if (pq_missing) {
286         ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
287                                         &ctx->P, &ctx->Q);
288         if (ret != 0) {
289             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
290         }
291 
292     } else if (d_missing) {
293         if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
294                                                        &ctx->Q,
295                                                        &ctx->E,
296                                                        &ctx->D)) != 0) {
297             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
298         }
299     }
300 
301     /*
302      * Step 3: Deduce all additional parameters specific
303      *         to our current RSA implementation.
304      */
305 
306 #if !defined(MBEDTLS_RSA_NO_CRT)
307     if (is_priv && !(have_DP && have_DQ && have_QP)) {
308         ret = mbedtls_rsa_deduce_crt(&ctx->P,  &ctx->Q,  &ctx->D,
309                                      &ctx->DP, &ctx->DQ, &ctx->QP);
310         if (ret != 0) {
311             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
312         }
313     }
314 #endif /* MBEDTLS_RSA_NO_CRT */
315 
316     /*
317      * Step 3: Basic sanity checks
318      */
319 
320     return rsa_check_context(ctx, is_priv, 1);
321 }
322 
323 int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
324                            unsigned char *N, size_t N_len,
325                            unsigned char *P, size_t P_len,
326                            unsigned char *Q, size_t Q_len,
327                            unsigned char *D, size_t D_len,
328                            unsigned char *E, size_t E_len)
329 {
330     int ret = 0;
331     int is_priv;
332 
333     /* Check if key is private or public */
334     is_priv =
335         mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
336         mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
337         mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
338         mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
339         mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
340 
341     if (!is_priv) {
342         /* If we're trying to export private parameters for a public key,
343          * something must be wrong. */
344         if (P != NULL || Q != NULL || D != NULL) {
345             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
346         }
347 
348     }
349 
350     if (N != NULL) {
351         MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
352     }
353 
354     if (P != NULL) {
355         MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
356     }
357 
358     if (Q != NULL) {
359         MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
360     }
361 
362     if (D != NULL) {
363         MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
364     }
365 
366     if (E != NULL) {
367         MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
368     }
369 
370 cleanup:
371 
372     return ret;
373 }
374 
375 int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
376                        mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
377                        mbedtls_mpi *D, mbedtls_mpi *E)
378 {
379     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
380     int is_priv;
381 
382     /* Check if key is private or public */
383     is_priv =
384         mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
385         mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
386         mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
387         mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
388         mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
389 
390     if (!is_priv) {
391         /* If we're trying to export private parameters for a public key,
392          * something must be wrong. */
393         if (P != NULL || Q != NULL || D != NULL) {
394             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
395         }
396 
397     }
398 
399     /* Export all requested core parameters. */
400 
401     if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
402         (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
403         (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
404         (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
405         (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
406         return ret;
407     }
408 
409     return 0;
410 }
411 
412 /*
413  * Export CRT parameters
414  * This must also be implemented if CRT is not used, for being able to
415  * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
416  * can be used in this case.
417  */
418 int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
419                            mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
420 {
421     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
422     int is_priv;
423 
424     /* Check if key is private or public */
425     is_priv =
426         mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
427         mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
428         mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
429         mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
430         mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
431 
432     if (!is_priv) {
433         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
434     }
435 
436 #if !defined(MBEDTLS_RSA_NO_CRT)
437     /* Export all requested blinding parameters. */
438     if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
439         (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
440         (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
441         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
442     }
443 #else
444     if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
445                                       DP, DQ, QP)) != 0) {
446         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
447     }
448 #endif
449 
450     return 0;
451 }
452 
453 /*
454  * Initialize an RSA context
455  */
456 void mbedtls_rsa_init(mbedtls_rsa_context *ctx)
457 {
458     memset(ctx, 0, sizeof(mbedtls_rsa_context));
459 
460     ctx->padding = MBEDTLS_RSA_PKCS_V15;
461     ctx->hash_id = MBEDTLS_MD_NONE;
462 
463 #if defined(MBEDTLS_THREADING_C)
464     /* Set ctx->ver to nonzero to indicate that the mutex has been
465      * initialized and will need to be freed. */
466     ctx->ver = 1;
467     mbedtls_mutex_init(&ctx->mutex);
468 #endif
469 }
470 
471 /*
472  * Set padding for an existing RSA context
473  */
474 int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
475                             mbedtls_md_type_t hash_id)
476 {
477     switch (padding) {
478 #if defined(MBEDTLS_PKCS1_V15)
479         case MBEDTLS_RSA_PKCS_V15:
480             break;
481 #endif
482 
483 #if defined(MBEDTLS_PKCS1_V21)
484         case MBEDTLS_RSA_PKCS_V21:
485             break;
486 #endif
487         default:
488             return MBEDTLS_ERR_RSA_INVALID_PADDING;
489     }
490 
491 #if defined(MBEDTLS_PKCS1_V21)
492     if ((padding == MBEDTLS_RSA_PKCS_V21) &&
493         (hash_id != MBEDTLS_MD_NONE)) {
494         /* Just make sure this hash is supported in this build. */
495         if (mbedtls_hash_info_psa_from_md(hash_id) == PSA_ALG_NONE) {
496             return MBEDTLS_ERR_RSA_INVALID_PADDING;
497         }
498     }
499 #endif /* MBEDTLS_PKCS1_V21 */
500 
501     ctx->padding = padding;
502     ctx->hash_id = hash_id;
503 
504     return 0;
505 }
506 
507 /*
508  * Get padding mode of initialized RSA context
509  */
510 int mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context *ctx)
511 {
512     return ctx->padding;
513 }
514 
515 /*
516  * Get hash identifier of mbedtls_md_type_t type
517  */
518 int mbedtls_rsa_get_md_alg(const mbedtls_rsa_context *ctx)
519 {
520     return ctx->hash_id;
521 }
522 
523 /*
524  * Get length in bytes of RSA modulus
525  */
526 size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
527 {
528     return ctx->len;
529 }
530 
531 
532 #if defined(MBEDTLS_GENPRIME)
533 
534 /*
535  * Generate an RSA keypair
536  *
537  * This generation method follows the RSA key pair generation procedure of
538  * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
539  */
540 int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
541                         int (*f_rng)(void *, unsigned char *, size_t),
542                         void *p_rng,
543                         unsigned int nbits, int exponent)
544 {
545     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
546     mbedtls_mpi H, G, L;
547     int prime_quality = 0;
548 
549     /*
550      * If the modulus is 1024 bit long or shorter, then the security strength of
551      * the RSA algorithm is less than or equal to 80 bits and therefore an error
552      * rate of 2^-80 is sufficient.
553      */
554     if (nbits > 1024) {
555         prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
556     }
557 
558     mbedtls_mpi_init(&H);
559     mbedtls_mpi_init(&G);
560     mbedtls_mpi_init(&L);
561 
562     if (nbits < 128 || exponent < 3 || nbits % 2 != 0) {
563         ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
564         goto cleanup;
565     }
566 
567     /*
568      * find primes P and Q with Q < P so that:
569      * 1.  |P-Q| > 2^( nbits / 2 - 100 )
570      * 2.  GCD( E, (P-1)*(Q-1) ) == 1
571      * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
572      */
573     MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
574 
575     do {
576         MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
577                                               prime_quality, f_rng, p_rng));
578 
579         MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
580                                               prime_quality, f_rng, p_rng));
581 
582         /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
583         MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
584         if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
585             continue;
586         }
587 
588         /* not required by any standards, but some users rely on the fact that P > Q */
589         if (H.s < 0) {
590             mbedtls_mpi_swap(&ctx->P, &ctx->Q);
591         }
592 
593         /* Temporarily replace P,Q by P-1, Q-1 */
594         MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
595         MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
596         MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
597 
598         /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
599         MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
600         if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
601             continue;
602         }
603 
604         /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
605         MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
606         MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
607         MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
608 
609         if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {      // (FIPS 186-4 §B.3.1 criterion 3(a))
610             continue;
611         }
612 
613         break;
614     } while (1);
615 
616     /* Restore P,Q */
617     MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P,  &ctx->P, 1));
618     MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q,  &ctx->Q, 1));
619 
620     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
621 
622     ctx->len = mbedtls_mpi_size(&ctx->N);
623 
624 #if !defined(MBEDTLS_RSA_NO_CRT)
625     /*
626      * DP = D mod (P - 1)
627      * DQ = D mod (Q - 1)
628      * QP = Q^-1 mod P
629      */
630     MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
631                                            &ctx->DP, &ctx->DQ, &ctx->QP));
632 #endif /* MBEDTLS_RSA_NO_CRT */
633 
634     /* Double-check */
635     MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
636 
637 cleanup:
638 
639     mbedtls_mpi_free(&H);
640     mbedtls_mpi_free(&G);
641     mbedtls_mpi_free(&L);
642 
643     if (ret != 0) {
644         mbedtls_rsa_free(ctx);
645 
646         if ((-ret & ~0x7f) == 0) {
647             ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
648         }
649         return ret;
650     }
651 
652     return 0;
653 }
654 
655 #endif /* MBEDTLS_GENPRIME */
656 
657 /*
658  * Check a public RSA key
659  */
660 int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
661 {
662     if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
663         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
664     }
665 
666     if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
667         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
668     }
669 
670     if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
671         mbedtls_mpi_bitlen(&ctx->E)     < 2  ||
672         mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
673         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
674     }
675 
676     return 0;
677 }
678 
679 /*
680  * Check for the consistency of all fields in an RSA private key context
681  */
682 int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
683 {
684     if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
685         rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
686         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
687     }
688 
689     if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
690                                     &ctx->D, &ctx->E, NULL, NULL) != 0) {
691         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
692     }
693 
694 #if !defined(MBEDTLS_RSA_NO_CRT)
695     else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
696                                       &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
697         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
698     }
699 #endif
700 
701     return 0;
702 }
703 
704 /*
705  * Check if contexts holding a public and private key match
706  */
707 int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
708                                const mbedtls_rsa_context *prv)
709 {
710     if (mbedtls_rsa_check_pubkey(pub)  != 0 ||
711         mbedtls_rsa_check_privkey(prv) != 0) {
712         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
713     }
714 
715     if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
716         mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
717         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
718     }
719 
720     return 0;
721 }
722 
723 /*
724  * Do an RSA public key operation
725  */
726 int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
727                        const unsigned char *input,
728                        unsigned char *output)
729 {
730     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
731     size_t olen;
732     mbedtls_mpi T;
733 
734     if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
735         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
736     }
737 
738     mbedtls_mpi_init(&T);
739 
740 #if defined(MBEDTLS_THREADING_C)
741     if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
742         return ret;
743     }
744 #endif
745 
746     MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
747 
748     if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
749         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
750         goto cleanup;
751     }
752 
753     olen = ctx->len;
754     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
755     MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
756 
757 cleanup:
758 #if defined(MBEDTLS_THREADING_C)
759     if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
760         return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
761     }
762 #endif
763 
764     mbedtls_mpi_free(&T);
765 
766     if (ret != 0) {
767         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
768     }
769 
770     return 0;
771 }
772 
773 /*
774  * Generate or update blinding values, see section 10 of:
775  *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
776  *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
777  *  Berlin Heidelberg, 1996. p. 104-113.
778  */
779 static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
780                                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
781 {
782     int ret, count = 0;
783     mbedtls_mpi R;
784 
785     mbedtls_mpi_init(&R);
786 
787     if (ctx->Vf.p != NULL) {
788         /* We already have blinding values, just update them by squaring */
789         MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
790         MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
791         MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
792         MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
793 
794         goto cleanup;
795     }
796 
797     /* Unblinding value: Vf = random number, invertible mod N */
798     do {
799         if (count++ > 10) {
800             ret = MBEDTLS_ERR_RSA_RNG_FAILED;
801             goto cleanup;
802         }
803 
804         MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
805 
806         /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
807         MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
808         MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
809         MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
810 
811         /* At this point, Vi is invertible mod N if and only if both Vf and R
812          * are invertible mod N. If one of them isn't, we don't need to know
813          * which one, we just loop and choose new values for both of them.
814          * (Each iteration succeeds with overwhelming probability.) */
815         ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
816         if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
817             goto cleanup;
818         }
819 
820     } while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
821 
822     /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
823     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
824     MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
825 
826     /* Blinding value: Vi = Vf^(-e) mod N
827      * (Vi already contains Vf^-1 at this point) */
828     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
829 
830 
831 cleanup:
832     mbedtls_mpi_free(&R);
833 
834     return ret;
835 }
836 
837 /*
838  * Exponent blinding supposed to prevent side-channel attacks using multiple
839  * traces of measurements to recover the RSA key. The more collisions are there,
840  * the more bits of the key can be recovered. See [3].
841  *
842  * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
843  * observations on average.
844  *
845  * For example with 28 byte blinding to achieve 2 collisions the adversary has
846  * to make 2^112 observations on average.
847  *
848  * (With the currently (as of 2017 April) known best algorithms breaking 2048
849  * bit RSA requires approximately as much time as trying out 2^112 random keys.
850  * Thus in this sense with 28 byte blinding the security is not reduced by
851  * side-channel attacks like the one in [3])
852  *
853  * This countermeasure does not help if the key recovery is possible with a
854  * single trace.
855  */
856 #define RSA_EXPONENT_BLINDING 28
857 
858 /*
859  * Do an RSA private key operation
860  */
861 int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
862                         int (*f_rng)(void *, unsigned char *, size_t),
863                         void *p_rng,
864                         const unsigned char *input,
865                         unsigned char *output)
866 {
867     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
868     size_t olen;
869 
870     /* Temporary holding the result */
871     mbedtls_mpi T;
872 
873     /* Temporaries holding P-1, Q-1 and the
874      * exponent blinding factor, respectively. */
875     mbedtls_mpi P1, Q1, R;
876 
877 #if !defined(MBEDTLS_RSA_NO_CRT)
878     /* Temporaries holding the results mod p resp. mod q. */
879     mbedtls_mpi TP, TQ;
880 
881     /* Temporaries holding the blinded exponents for
882      * the mod p resp. mod q computation (if used). */
883     mbedtls_mpi DP_blind, DQ_blind;
884 
885     /* Pointers to actual exponents to be used - either the unblinded
886      * or the blinded ones, depending on the presence of a PRNG. */
887     mbedtls_mpi *DP = &ctx->DP;
888     mbedtls_mpi *DQ = &ctx->DQ;
889 #else
890     /* Temporary holding the blinded exponent (if used). */
891     mbedtls_mpi D_blind;
892 
893     /* Pointer to actual exponent to be used - either the unblinded
894      * or the blinded one, depending on the presence of a PRNG. */
895     mbedtls_mpi *D = &ctx->D;
896 #endif /* MBEDTLS_RSA_NO_CRT */
897 
898     /* Temporaries holding the initial input and the double
899      * checked result; should be the same in the end. */
900     mbedtls_mpi I, C;
901 
902     if (f_rng == NULL) {
903         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
904     }
905 
906     if (rsa_check_context(ctx, 1 /* private key checks */,
907                           1 /* blinding on        */) != 0) {
908         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
909     }
910 
911 #if defined(MBEDTLS_THREADING_C)
912     if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
913         return ret;
914     }
915 #endif
916 
917     /* MPI Initialization */
918     mbedtls_mpi_init(&T);
919 
920     mbedtls_mpi_init(&P1);
921     mbedtls_mpi_init(&Q1);
922     mbedtls_mpi_init(&R);
923 
924 #if defined(MBEDTLS_RSA_NO_CRT)
925     mbedtls_mpi_init(&D_blind);
926 #else
927     mbedtls_mpi_init(&DP_blind);
928     mbedtls_mpi_init(&DQ_blind);
929 #endif
930 
931 #if !defined(MBEDTLS_RSA_NO_CRT)
932     mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
933 #endif
934 
935     mbedtls_mpi_init(&I);
936     mbedtls_mpi_init(&C);
937 
938     /* End of MPI initialization */
939 
940     MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
941     if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
942         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
943         goto cleanup;
944     }
945 
946     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&I, &T));
947 
948     /*
949      * Blinding
950      * T = T * Vi mod N
951      */
952     MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
953     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
954     MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
955 
956     /*
957      * Exponent blinding
958      */
959     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
960     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
961 
962 #if defined(MBEDTLS_RSA_NO_CRT)
963     /*
964      * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
965      */
966     MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
967                                             f_rng, p_rng));
968     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
969     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
970     MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
971 
972     D = &D_blind;
973 #else
974     /*
975      * DP_blind = ( P - 1 ) * R + DP
976      */
977     MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
978                                             f_rng, p_rng));
979     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
980     MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
981                                         &ctx->DP));
982 
983     DP = &DP_blind;
984 
985     /*
986      * DQ_blind = ( Q - 1 ) * R + DQ
987      */
988     MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
989                                             f_rng, p_rng));
990     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
991     MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
992                                         &ctx->DQ));
993 
994     DQ = &DQ_blind;
995 #endif /* MBEDTLS_RSA_NO_CRT */
996 
997 #if defined(MBEDTLS_RSA_NO_CRT)
998     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, D, &ctx->N, &ctx->RN));
999 #else
1000     /*
1001      * Faster decryption using the CRT
1002      *
1003      * TP = input ^ dP mod P
1004      * TQ = input ^ dQ mod Q
1005      */
1006 
1007     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, DP, &ctx->P, &ctx->RP));
1008     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, DQ, &ctx->Q, &ctx->RQ));
1009 
1010     /*
1011      * T = (TP - TQ) * (Q^-1 mod P) mod P
1012      */
1013     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
1014     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
1015     MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
1016 
1017     /*
1018      * T = TQ + T * Q
1019      */
1020     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1021     MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1022 #endif /* MBEDTLS_RSA_NO_CRT */
1023 
1024     /*
1025      * Unblind
1026      * T = T * Vf mod N
1027      */
1028     MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vf));
1029     MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
1030 
1031     /* Verify the result to prevent glitching attacks. */
1032     MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&C, &T, &ctx->E,
1033                                         &ctx->N, &ctx->RN));
1034     if (mbedtls_mpi_cmp_mpi(&C, &I) != 0) {
1035         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1036         goto cleanup;
1037     }
1038 
1039     olen = ctx->len;
1040     MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1041 
1042 cleanup:
1043 #if defined(MBEDTLS_THREADING_C)
1044     if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1045         return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1046     }
1047 #endif
1048 
1049     mbedtls_mpi_free(&P1);
1050     mbedtls_mpi_free(&Q1);
1051     mbedtls_mpi_free(&R);
1052 
1053 #if defined(MBEDTLS_RSA_NO_CRT)
1054     mbedtls_mpi_free(&D_blind);
1055 #else
1056     mbedtls_mpi_free(&DP_blind);
1057     mbedtls_mpi_free(&DQ_blind);
1058 #endif
1059 
1060     mbedtls_mpi_free(&T);
1061 
1062 #if !defined(MBEDTLS_RSA_NO_CRT)
1063     mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1064 #endif
1065 
1066     mbedtls_mpi_free(&C);
1067     mbedtls_mpi_free(&I);
1068 
1069     if (ret != 0 && ret >= -0x007f) {
1070         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1071     }
1072 
1073     return ret;
1074 }
1075 
1076 #if defined(MBEDTLS_PKCS1_V21)
1077 /**
1078  * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1079  *
1080  * \param dst       buffer to mask
1081  * \param dlen      length of destination buffer
1082  * \param src       source of the mask generation
1083  * \param slen      length of the source buffer
1084  * \param md_alg    message digest to use
1085  */
1086 static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1087                     size_t slen, mbedtls_md_type_t md_alg)
1088 {
1089     unsigned char counter[4];
1090     unsigned char *p;
1091     unsigned int hlen;
1092     size_t i, use_len;
1093     unsigned char mask[MBEDTLS_HASH_MAX_SIZE];
1094 #if defined(MBEDTLS_MD_C)
1095     int ret = 0;
1096     const mbedtls_md_info_t *md_info;
1097     mbedtls_md_context_t md_ctx;
1098 
1099     mbedtls_md_init(&md_ctx);
1100     md_info = mbedtls_md_info_from_type(md_alg);
1101     if (md_info == NULL) {
1102         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1103     }
1104 
1105     mbedtls_md_init(&md_ctx);
1106     if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1107         goto exit;
1108     }
1109 
1110     hlen = mbedtls_md_get_size(md_info);
1111 #else
1112     psa_hash_operation_t op = PSA_HASH_OPERATION_INIT;
1113     psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1114     psa_status_t status = PSA_SUCCESS;
1115     size_t out_len;
1116 
1117     hlen = PSA_HASH_LENGTH(alg);
1118 #endif
1119 
1120     memset(mask, 0, sizeof(mask));
1121     memset(counter, 0, 4);
1122 
1123     /* Generate and apply dbMask */
1124     p = dst;
1125 
1126     while (dlen > 0) {
1127         use_len = hlen;
1128         if (dlen < hlen) {
1129             use_len = dlen;
1130         }
1131 
1132 #if defined(MBEDTLS_MD_C)
1133         if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1134             goto exit;
1135         }
1136         if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
1137             goto exit;
1138         }
1139         if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
1140             goto exit;
1141         }
1142         if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
1143             goto exit;
1144         }
1145 #else
1146         if ((status = psa_hash_setup(&op, alg)) != PSA_SUCCESS) {
1147             goto exit;
1148         }
1149         if ((status = psa_hash_update(&op, src, slen)) != PSA_SUCCESS) {
1150             goto exit;
1151         }
1152         if ((status = psa_hash_update(&op, counter, 4)) != PSA_SUCCESS) {
1153             goto exit;
1154         }
1155         status = psa_hash_finish(&op, mask, sizeof(mask), &out_len);
1156         if (status != PSA_SUCCESS) {
1157             goto exit;
1158         }
1159 #endif
1160 
1161         for (i = 0; i < use_len; ++i) {
1162             *p++ ^= mask[i];
1163         }
1164 
1165         counter[3]++;
1166 
1167         dlen -= use_len;
1168     }
1169 
1170 exit:
1171     mbedtls_platform_zeroize(mask, sizeof(mask));
1172 #if defined(MBEDTLS_MD_C)
1173     mbedtls_md_free(&md_ctx);
1174 
1175     return ret;
1176 #else
1177     psa_hash_abort(&op);
1178 
1179     return PSA_TO_MBEDTLS_ERR(status);
1180 #endif
1181 }
1182 
1183 /**
1184  * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
1185  *
1186  * \param hash      the input hash
1187  * \param hlen      length of the input hash
1188  * \param salt      the input salt
1189  * \param slen      length of the input salt
1190  * \param out       the output buffer - must be large enough for \p md_alg
1191  * \param md_alg    message digest to use
1192  */
1193 static int hash_mprime(const unsigned char *hash, size_t hlen,
1194                        const unsigned char *salt, size_t slen,
1195                        unsigned char *out, mbedtls_md_type_t md_alg)
1196 {
1197     const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1198 
1199 #if defined(MBEDTLS_MD_C)
1200     mbedtls_md_context_t md_ctx;
1201     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1202 
1203     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1204     if (md_info == NULL) {
1205         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1206     }
1207 
1208     mbedtls_md_init(&md_ctx);
1209     if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1210         goto exit;
1211     }
1212     if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1213         goto exit;
1214     }
1215     if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
1216         goto exit;
1217     }
1218     if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
1219         goto exit;
1220     }
1221     if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1222         goto exit;
1223     }
1224     if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
1225         goto exit;
1226     }
1227 
1228 exit:
1229     mbedtls_md_free(&md_ctx);
1230 
1231     return ret;
1232 #else
1233     psa_hash_operation_t op = PSA_HASH_OPERATION_INIT;
1234     psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1235     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1236     size_t out_size = PSA_HASH_LENGTH(alg);
1237     size_t out_len;
1238 
1239     if ((status = psa_hash_setup(&op, alg)) != PSA_SUCCESS) {
1240         goto exit;
1241     }
1242     if ((status = psa_hash_update(&op, zeros, sizeof(zeros))) != PSA_SUCCESS) {
1243         goto exit;
1244     }
1245     if ((status = psa_hash_update(&op, hash, hlen)) != PSA_SUCCESS) {
1246         goto exit;
1247     }
1248     if ((status = psa_hash_update(&op, salt, slen)) != PSA_SUCCESS) {
1249         goto exit;
1250     }
1251     status = psa_hash_finish(&op, out, out_size, &out_len);
1252     if (status != PSA_SUCCESS) {
1253         goto exit;
1254     }
1255 
1256 exit:
1257     psa_hash_abort(&op);
1258 
1259     return PSA_TO_MBEDTLS_ERR(status);
1260 #endif /* !MBEDTLS_MD_C */
1261 }
1262 
1263 /**
1264  * Compute a hash.
1265  *
1266  * \param md_alg    algorithm to use
1267  * \param input     input message to hash
1268  * \param ilen      input length
1269  * \param output    the output buffer - must be large enough for \p md_alg
1270  */
1271 static int compute_hash(mbedtls_md_type_t md_alg,
1272                         const unsigned char *input, size_t ilen,
1273                         unsigned char *output)
1274 {
1275 #if defined(MBEDTLS_MD_C)
1276     const mbedtls_md_info_t *md_info;
1277 
1278     md_info = mbedtls_md_info_from_type(md_alg);
1279     if (md_info == NULL) {
1280         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1281     }
1282 
1283     return mbedtls_md(md_info, input, ilen, output);
1284 #else
1285     psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1286     psa_status_t status;
1287     size_t out_size = PSA_HASH_LENGTH(alg);
1288     size_t out_len;
1289 
1290     status = psa_hash_compute(alg, input, ilen, output, out_size, &out_len);
1291 
1292     return PSA_TO_MBEDTLS_ERR(status);
1293 #endif /* !MBEDTLS_MD_C */
1294 }
1295 #endif /* MBEDTLS_PKCS1_V21 */
1296 
1297 #if defined(MBEDTLS_PKCS1_V21)
1298 /*
1299  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1300  */
1301 int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1302                                    int (*f_rng)(void *, unsigned char *, size_t),
1303                                    void *p_rng,
1304                                    const unsigned char *label, size_t label_len,
1305                                    size_t ilen,
1306                                    const unsigned char *input,
1307                                    unsigned char *output)
1308 {
1309     size_t olen;
1310     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1311     unsigned char *p = output;
1312     unsigned int hlen;
1313 
1314     if (f_rng == NULL) {
1315         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1316     }
1317 
1318     hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1319     if (hlen == 0) {
1320         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1321     }
1322 
1323     olen = ctx->len;
1324 
1325     /* first comparison checks for overflow */
1326     if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1327         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1328     }
1329 
1330     memset(output, 0, olen);
1331 
1332     *p++ = 0;
1333 
1334     /* Generate a random octet string seed */
1335     if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1336         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1337     }
1338 
1339     p += hlen;
1340 
1341     /* Construct DB */
1342     ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
1343     if (ret != 0) {
1344         return ret;
1345     }
1346     p += hlen;
1347     p += olen - 2 * hlen - 2 - ilen;
1348     *p++ = 1;
1349     if (ilen != 0) {
1350         memcpy(p, input, ilen);
1351     }
1352 
1353     /* maskedDB: Apply dbMask to DB */
1354     if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1355                         ctx->hash_id)) != 0) {
1356         return ret;
1357     }
1358 
1359     /* maskedSeed: Apply seedMask to seed */
1360     if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1361                         ctx->hash_id)) != 0) {
1362         return ret;
1363     }
1364 
1365     return mbedtls_rsa_public(ctx, output, output);
1366 }
1367 #endif /* MBEDTLS_PKCS1_V21 */
1368 
1369 #if defined(MBEDTLS_PKCS1_V15)
1370 /*
1371  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1372  */
1373 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1374                                         int (*f_rng)(void *, unsigned char *, size_t),
1375                                         void *p_rng, size_t ilen,
1376                                         const unsigned char *input,
1377                                         unsigned char *output)
1378 {
1379     size_t nb_pad, olen;
1380     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1381     unsigned char *p = output;
1382 
1383     olen = ctx->len;
1384 
1385     /* first comparison checks for overflow */
1386     if (ilen + 11 < ilen || olen < ilen + 11) {
1387         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1388     }
1389 
1390     nb_pad = olen - 3 - ilen;
1391 
1392     *p++ = 0;
1393 
1394     if (f_rng == NULL) {
1395         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1396     }
1397 
1398     *p++ = MBEDTLS_RSA_CRYPT;
1399 
1400     while (nb_pad-- > 0) {
1401         int rng_dl = 100;
1402 
1403         do {
1404             ret = f_rng(p_rng, p, 1);
1405         } while (*p == 0 && --rng_dl && ret == 0);
1406 
1407         /* Check if RNG failed to generate data */
1408         if (rng_dl == 0 || ret != 0) {
1409             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1410         }
1411 
1412         p++;
1413     }
1414 
1415     *p++ = 0;
1416     if (ilen != 0) {
1417         memcpy(p, input, ilen);
1418     }
1419 
1420     return mbedtls_rsa_public(ctx, output, output);
1421 }
1422 #endif /* MBEDTLS_PKCS1_V15 */
1423 
1424 /*
1425  * Add the message padding, then do an RSA operation
1426  */
1427 int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1428                               int (*f_rng)(void *, unsigned char *, size_t),
1429                               void *p_rng,
1430                               size_t ilen,
1431                               const unsigned char *input,
1432                               unsigned char *output)
1433 {
1434     switch (ctx->padding) {
1435 #if defined(MBEDTLS_PKCS1_V15)
1436         case MBEDTLS_RSA_PKCS_V15:
1437             return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
1438                                                        ilen, input, output);
1439 #endif
1440 
1441 #if defined(MBEDTLS_PKCS1_V21)
1442         case MBEDTLS_RSA_PKCS_V21:
1443             return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
1444                                                   ilen, input, output);
1445 #endif
1446 
1447         default:
1448             return MBEDTLS_ERR_RSA_INVALID_PADDING;
1449     }
1450 }
1451 
1452 #if defined(MBEDTLS_PKCS1_V21)
1453 /*
1454  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1455  */
1456 int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1457                                    int (*f_rng)(void *, unsigned char *, size_t),
1458                                    void *p_rng,
1459                                    const unsigned char *label, size_t label_len,
1460                                    size_t *olen,
1461                                    const unsigned char *input,
1462                                    unsigned char *output,
1463                                    size_t output_max_len)
1464 {
1465     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1466     size_t ilen, i, pad_len;
1467     unsigned char *p, bad, pad_done;
1468     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1469     unsigned char lhash[MBEDTLS_HASH_MAX_SIZE];
1470     unsigned int hlen;
1471 
1472     /*
1473      * Parameters sanity checks
1474      */
1475     if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1476         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1477     }
1478 
1479     ilen = ctx->len;
1480 
1481     if (ilen < 16 || ilen > sizeof(buf)) {
1482         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1483     }
1484 
1485     hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1486     if (hlen == 0) {
1487         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1488     }
1489 
1490     // checking for integer underflow
1491     if (2 * hlen + 2 > ilen) {
1492         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1493     }
1494 
1495     /*
1496      * RSA operation
1497      */
1498     if( ctx->P.n == 0 )
1499         ret = mbedtls_rsa_private( ctx, NULL, NULL, input, buf );
1500     else
1501         ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1502 
1503     if (ret != 0) {
1504         goto cleanup;
1505     }
1506 
1507     /*
1508      * Unmask data and generate lHash
1509      */
1510     /* seed: Apply seedMask to maskedSeed */
1511     if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1512                         ctx->hash_id)) != 0 ||
1513         /* DB: Apply dbMask to maskedDB */
1514         (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1515                         ctx->hash_id)) != 0) {
1516         goto cleanup;
1517     }
1518 
1519     /* Generate lHash */
1520     ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
1521                        label, label_len, lhash);
1522     if (ret != 0) {
1523         goto cleanup;
1524     }
1525 
1526     /*
1527      * Check contents, in "constant-time"
1528      */
1529     p = buf;
1530     bad = 0;
1531 
1532     bad |= *p++; /* First byte must be 0 */
1533 
1534     p += hlen; /* Skip seed */
1535 
1536     /* Check lHash */
1537     for (i = 0; i < hlen; i++) {
1538         bad |= lhash[i] ^ *p++;
1539     }
1540 
1541     /* Get zero-padding len, but always read till end of buffer
1542      * (minus one, for the 01 byte) */
1543     pad_len = 0;
1544     pad_done = 0;
1545     for (i = 0; i < ilen - 2 * hlen - 2; i++) {
1546         pad_done |= p[i];
1547         pad_len += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
1548     }
1549 
1550     p += pad_len;
1551     bad |= *p++ ^ 0x01;
1552 
1553     /*
1554      * The only information "leaked" is whether the padding was correct or not
1555      * (eg, no data is copied if it was not correct). This meets the
1556      * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
1557      * the different error conditions.
1558      */
1559     if (bad != 0) {
1560         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
1561         goto cleanup;
1562     }
1563 
1564     if (ilen - (p - buf) > output_max_len) {
1565         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1566         goto cleanup;
1567     }
1568 
1569     *olen = ilen - (p - buf);
1570     if (*olen != 0) {
1571         memcpy(output, p, *olen);
1572     }
1573     ret = 0;
1574 
1575 cleanup:
1576     mbedtls_platform_zeroize(buf, sizeof(buf));
1577     mbedtls_platform_zeroize(lhash, sizeof(lhash));
1578 
1579     return ret;
1580 }
1581 #endif /* MBEDTLS_PKCS1_V21 */
1582 
1583 #if defined(MBEDTLS_PKCS1_V15)
1584 /*
1585  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
1586  */
1587 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
1588                                         int (*f_rng)(void *, unsigned char *, size_t),
1589                                         void *p_rng,
1590                                         size_t *olen,
1591                                         const unsigned char *input,
1592                                         unsigned char *output,
1593                                         size_t output_max_len)
1594 {
1595     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1596     size_t ilen;
1597     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1598 
1599     ilen = ctx->len;
1600 
1601     if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1602         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1603     }
1604 
1605     if (ilen < 16 || ilen > sizeof(buf)) {
1606         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1607     }
1608 
1609     ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1610 
1611     if (ret != 0) {
1612         goto cleanup;
1613     }
1614 
1615     ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
1616                                                output, output_max_len, olen);
1617 
1618 cleanup:
1619     mbedtls_platform_zeroize(buf, sizeof(buf));
1620 
1621     return ret;
1622 }
1623 #endif /* MBEDTLS_PKCS1_V15 */
1624 
1625 /*
1626  * Do an RSA operation, then remove the message padding
1627  */
1628 int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
1629                               int (*f_rng)(void *, unsigned char *, size_t),
1630                               void *p_rng,
1631                               size_t *olen,
1632                               const unsigned char *input,
1633                               unsigned char *output,
1634                               size_t output_max_len)
1635 {
1636     switch (ctx->padding) {
1637 #if defined(MBEDTLS_PKCS1_V15)
1638         case MBEDTLS_RSA_PKCS_V15:
1639             return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
1640                                                        input, output, output_max_len);
1641 #endif
1642 
1643 #if defined(MBEDTLS_PKCS1_V21)
1644         case MBEDTLS_RSA_PKCS_V21:
1645             return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
1646                                                   olen, input, output,
1647                                                   output_max_len);
1648 #endif
1649 
1650         default:
1651             return MBEDTLS_ERR_RSA_INVALID_PADDING;
1652     }
1653 }
1654 
1655 #if defined(MBEDTLS_PKCS1_V21)
1656 static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1657                                int (*f_rng)(void *, unsigned char *, size_t),
1658                                void *p_rng,
1659                                mbedtls_md_type_t md_alg,
1660                                unsigned int hashlen,
1661                                const unsigned char *hash,
1662                                int saltlen,
1663                                unsigned char *sig)
1664 {
1665     size_t olen;
1666     unsigned char *p = sig;
1667     unsigned char *salt = NULL;
1668     size_t slen, min_slen, hlen, offset = 0;
1669     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1670     size_t msb;
1671 
1672     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
1673         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1674     }
1675 
1676     if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1677         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1678     }
1679 
1680     if (f_rng == NULL) {
1681         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1682     }
1683 
1684     olen = ctx->len;
1685 
1686     if (md_alg != MBEDTLS_MD_NONE) {
1687         /* Gather length of hash to sign */
1688         size_t exp_hashlen = mbedtls_hash_info_get_size(md_alg);
1689         if (exp_hashlen == 0) {
1690             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1691         }
1692 
1693         if (hashlen != exp_hashlen) {
1694             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1695         }
1696     }
1697 
1698     hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1699     if (hlen == 0) {
1700         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1701     }
1702 
1703     if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
1704         /* Calculate the largest possible salt length, up to the hash size.
1705          * Normally this is the hash length, which is the maximum salt length
1706          * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
1707          * enough room, use the maximum salt length that fits. The constraint is
1708          * that the hash length plus the salt length plus 2 bytes must be at most
1709          * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
1710          * (PKCS#1 v2.2) §9.1.1 step 3. */
1711         min_slen = hlen - 2;
1712         if (olen < hlen + min_slen + 2) {
1713             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1714         } else if (olen >= hlen + hlen + 2) {
1715             slen = hlen;
1716         } else {
1717             slen = olen - hlen - 2;
1718         }
1719     } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
1720         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1721     } else {
1722         slen = (size_t) saltlen;
1723     }
1724 
1725     memset(sig, 0, olen);
1726 
1727     /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
1728     msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1729     p += olen - hlen - slen - 2;
1730     *p++ = 0x01;
1731 
1732     /* Generate salt of length slen in place in the encoded message */
1733     salt = p;
1734     if ((ret = f_rng(p_rng, salt, slen)) != 0) {
1735         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1736     }
1737 
1738     p += slen;
1739 
1740     /* Generate H = Hash( M' ) */
1741     ret = hash_mprime(hash, hashlen, salt, slen, p, ctx->hash_id);
1742     if (ret != 0) {
1743         return ret;
1744     }
1745 
1746     /* Compensate for boundary condition when applying mask */
1747     if (msb % 8 == 0) {
1748         offset = 1;
1749     }
1750 
1751     /* maskedDB: Apply dbMask to DB */
1752     ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen,
1753                    ctx->hash_id);
1754     if (ret != 0) {
1755         return ret;
1756     }
1757 
1758     msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1759     sig[0] &= 0xFF >> (olen * 8 - msb);
1760 
1761     p += hlen;
1762     *p++ = 0xBC;
1763 
1764     if (ctx->P.n == 0)
1765         return mbedtls_rsa_private(ctx, NULL, NULL, sig, sig);
1766 
1767     return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
1768 }
1769 
1770 /*
1771  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
1772  * the option to pass in the salt length.
1773  */
1774 int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
1775                                     int (*f_rng)(void *, unsigned char *, size_t),
1776                                     void *p_rng,
1777                                     mbedtls_md_type_t md_alg,
1778                                     unsigned int hashlen,
1779                                     const unsigned char *hash,
1780                                     int saltlen,
1781                                     unsigned char *sig)
1782 {
1783     return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
1784                                hashlen, hash, saltlen, sig);
1785 }
1786 
1787 
1788 /*
1789  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
1790  */
1791 int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1792                                 int (*f_rng)(void *, unsigned char *, size_t),
1793                                 void *p_rng,
1794                                 mbedtls_md_type_t md_alg,
1795                                 unsigned int hashlen,
1796                                 const unsigned char *hash,
1797                                 unsigned char *sig)
1798 {
1799     return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
1800                                hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
1801 }
1802 #endif /* MBEDTLS_PKCS1_V21 */
1803 
1804 #if defined(MBEDTLS_PKCS1_V15)
1805 /*
1806  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
1807  */
1808 
1809 /* Construct a PKCS v1.5 encoding of a hashed message
1810  *
1811  * This is used both for signature generation and verification.
1812  *
1813  * Parameters:
1814  * - md_alg:  Identifies the hash algorithm used to generate the given hash;
1815  *            MBEDTLS_MD_NONE if raw data is signed.
1816  * - hashlen: Length of hash. Must match md_alg if that's not NONE.
1817  * - hash:    Buffer containing the hashed message or the raw data.
1818  * - dst_len: Length of the encoded message.
1819  * - dst:     Buffer to hold the encoded message.
1820  *
1821  * Assumptions:
1822  * - hash has size hashlen.
1823  * - dst points to a buffer of size at least dst_len.
1824  *
1825  */
1826 static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
1827                                        unsigned int hashlen,
1828                                        const unsigned char *hash,
1829                                        size_t dst_len,
1830                                        unsigned char *dst)
1831 {
1832     size_t oid_size  = 0;
1833     size_t nb_pad    = dst_len;
1834     unsigned char *p = dst;
1835     const char *oid  = NULL;
1836 
1837     /* Are we signing hashed or raw data? */
1838     if (md_alg != MBEDTLS_MD_NONE) {
1839         unsigned char md_size = mbedtls_hash_info_get_size(md_alg);
1840         if (md_size == 0) {
1841             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1842         }
1843 
1844         if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
1845             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1846         }
1847 
1848         if (hashlen != md_size) {
1849             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1850         }
1851 
1852         /* Double-check that 8 + hashlen + oid_size can be used as a
1853          * 1-byte ASN.1 length encoding and that there's no overflow. */
1854         if (8 + hashlen + oid_size  >= 0x80         ||
1855             10 + hashlen            <  hashlen      ||
1856             10 + hashlen + oid_size <  10 + hashlen) {
1857             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1858         }
1859 
1860         /*
1861          * Static bounds check:
1862          * - Need 10 bytes for five tag-length pairs.
1863          *   (Insist on 1-byte length encodings to protect against variants of
1864          *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
1865          * - Need hashlen bytes for hash
1866          * - Need oid_size bytes for hash alg OID.
1867          */
1868         if (nb_pad < 10 + hashlen + oid_size) {
1869             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1870         }
1871         nb_pad -= 10 + hashlen + oid_size;
1872     } else {
1873         if (nb_pad < hashlen) {
1874             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1875         }
1876 
1877         nb_pad -= hashlen;
1878     }
1879 
1880     /* Need space for signature header and padding delimiter (3 bytes),
1881      * and 8 bytes for the minimal padding */
1882     if (nb_pad < 3 + 8) {
1883         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1884     }
1885     nb_pad -= 3;
1886 
1887     /* Now nb_pad is the amount of memory to be filled
1888      * with padding, and at least 8 bytes long. */
1889 
1890     /* Write signature header and padding */
1891     *p++ = 0;
1892     *p++ = MBEDTLS_RSA_SIGN;
1893     memset(p, 0xFF, nb_pad);
1894     p += nb_pad;
1895     *p++ = 0;
1896 
1897     /* Are we signing raw data? */
1898     if (md_alg == MBEDTLS_MD_NONE) {
1899         memcpy(p, hash, hashlen);
1900         return 0;
1901     }
1902 
1903     /* Signing hashed data, add corresponding ASN.1 structure
1904      *
1905      * DigestInfo ::= SEQUENCE {
1906      *   digestAlgorithm DigestAlgorithmIdentifier,
1907      *   digest Digest }
1908      * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1909      * Digest ::= OCTET STRING
1910      *
1911      * Schematic:
1912      * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
1913      *                                 TAG-NULL + LEN [ NULL ] ]
1914      *                 TAG-OCTET + LEN [ HASH ] ]
1915      */
1916     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1917     *p++ = (unsigned char) (0x08 + oid_size + hashlen);
1918     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1919     *p++ = (unsigned char) (0x04 + oid_size);
1920     *p++ = MBEDTLS_ASN1_OID;
1921     *p++ = (unsigned char) oid_size;
1922     memcpy(p, oid, oid_size);
1923     p += oid_size;
1924     *p++ = MBEDTLS_ASN1_NULL;
1925     *p++ = 0x00;
1926     *p++ = MBEDTLS_ASN1_OCTET_STRING;
1927     *p++ = (unsigned char) hashlen;
1928     memcpy(p, hash, hashlen);
1929     p += hashlen;
1930 
1931     /* Just a sanity-check, should be automatic
1932      * after the initial bounds check. */
1933     if (p != dst + dst_len) {
1934         mbedtls_platform_zeroize(dst, dst_len);
1935         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1936     }
1937 
1938     return 0;
1939 }
1940 
1941 /*
1942  * Do an RSA operation to sign the message digest
1943  */
1944 int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
1945                                       int (*f_rng)(void *, unsigned char *, size_t),
1946                                       void *p_rng,
1947                                       mbedtls_md_type_t md_alg,
1948                                       unsigned int hashlen,
1949                                       const unsigned char *hash,
1950                                       unsigned char *sig)
1951 {
1952     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1953     unsigned char *sig_try = NULL, *verif = NULL;
1954 
1955     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
1956         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1957     }
1958 
1959     if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1960         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1961     }
1962 
1963     /*
1964      * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
1965      */
1966 
1967     if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
1968                                            ctx->len, sig)) != 0) {
1969         return ret;
1970     }
1971 
1972     /* Private key operation
1973      *
1974      * In order to prevent Lenstra's attack, make the signature in a
1975      * temporary buffer and check it before returning it.
1976      */
1977 
1978     sig_try = mbedtls_calloc(1, ctx->len);
1979     if (sig_try == NULL) {
1980         return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1981     }
1982 
1983     verif = mbedtls_calloc(1, ctx->len);
1984     if (verif == NULL) {
1985         mbedtls_free(sig_try);
1986         return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1987     }
1988 
1989     MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
1990     MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
1991 
1992     if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
1993         ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
1994         goto cleanup;
1995     }
1996 
1997     memcpy(sig, sig_try, ctx->len);
1998 
1999 cleanup:
2000     mbedtls_platform_zeroize(sig_try, ctx->len);
2001     mbedtls_platform_zeroize(verif, ctx->len);
2002     mbedtls_free(sig_try);
2003     mbedtls_free(verif);
2004 
2005     if (ret != 0) {
2006         memset(sig, '!', ctx->len);
2007     }
2008     return ret;
2009 }
2010 #endif /* MBEDTLS_PKCS1_V15 */
2011 
2012 /*
2013  * Do an RSA operation to sign the message digest
2014  */
2015 int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
2016                            int (*f_rng)(void *, unsigned char *, size_t),
2017                            void *p_rng,
2018                            mbedtls_md_type_t md_alg,
2019                            unsigned int hashlen,
2020                            const unsigned char *hash,
2021                            unsigned char *sig)
2022 {
2023     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2024         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2025     }
2026 
2027     switch (ctx->padding) {
2028 #if defined(MBEDTLS_PKCS1_V15)
2029         case MBEDTLS_RSA_PKCS_V15:
2030             return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
2031                                                      md_alg, hashlen, hash, sig);
2032 #endif
2033 
2034 #if defined(MBEDTLS_PKCS1_V21)
2035         case MBEDTLS_RSA_PKCS_V21:
2036             return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2037                                                hashlen, hash, sig);
2038 #endif
2039 
2040         default:
2041             return MBEDTLS_ERR_RSA_INVALID_PADDING;
2042     }
2043 }
2044 
2045 #if defined(MBEDTLS_PKCS1_V21)
2046 /*
2047  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2048  */
2049 int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2050                                       mbedtls_md_type_t md_alg,
2051                                       unsigned int hashlen,
2052                                       const unsigned char *hash,
2053                                       mbedtls_md_type_t mgf1_hash_id,
2054                                       int expected_salt_len,
2055                                       const unsigned char *sig)
2056 {
2057     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2058     size_t siglen;
2059     unsigned char *p;
2060     unsigned char *hash_start;
2061     unsigned char result[MBEDTLS_HASH_MAX_SIZE];
2062     unsigned int hlen;
2063     size_t observed_salt_len, msb;
2064     unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
2065 
2066     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2067         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2068     }
2069 
2070     siglen = ctx->len;
2071 
2072     if (siglen < 16 || siglen > sizeof(buf)) {
2073         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2074     }
2075 
2076     ret = mbedtls_rsa_public(ctx, sig, buf);
2077 
2078     if (ret != 0) {
2079         return ret;
2080     }
2081 
2082     p = buf;
2083 
2084     if (buf[siglen - 1] != 0xBC) {
2085         return MBEDTLS_ERR_RSA_INVALID_PADDING;
2086     }
2087 
2088     if (md_alg != MBEDTLS_MD_NONE) {
2089         /* Gather length of hash to sign */
2090         size_t exp_hashlen = mbedtls_hash_info_get_size(md_alg);
2091         if (exp_hashlen == 0) {
2092             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2093         }
2094 
2095         if (hashlen != exp_hashlen) {
2096             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2097         }
2098     }
2099 
2100     hlen = mbedtls_hash_info_get_size(mgf1_hash_id);
2101     if (hlen == 0) {
2102         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2103     }
2104 
2105     /*
2106      * Note: EMSA-PSS verification is over the length of N - 1 bits
2107      */
2108     msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2109 
2110     if (buf[0] >> (8 - siglen * 8 + msb)) {
2111         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2112     }
2113 
2114     /* Compensate for boundary condition when applying mask */
2115     if (msb % 8 == 0) {
2116         p++;
2117         siglen -= 1;
2118     }
2119 
2120     if (siglen < hlen + 2) {
2121         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2122     }
2123     hash_start = p + siglen - hlen - 1;
2124 
2125     ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
2126     if (ret != 0) {
2127         return ret;
2128     }
2129 
2130     buf[0] &= 0xFF >> (siglen * 8 - msb);
2131 
2132     while (p < hash_start - 1 && *p == 0) {
2133         p++;
2134     }
2135 
2136     if (*p++ != 0x01) {
2137         return MBEDTLS_ERR_RSA_INVALID_PADDING;
2138     }
2139 
2140     observed_salt_len = hash_start - p;
2141 
2142     if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2143         observed_salt_len != (size_t) expected_salt_len) {
2144         return MBEDTLS_ERR_RSA_INVALID_PADDING;
2145     }
2146 
2147     /*
2148      * Generate H = Hash( M' )
2149      */
2150     ret = hash_mprime(hash, hashlen, p, observed_salt_len,
2151                       result, mgf1_hash_id);
2152     if (ret != 0) {
2153         return ret;
2154     }
2155 
2156     if (FTMN_CALLEE_DONE_MEMCMP(memcmp, hash_start, result, hlen) != 0) {
2157         return MBEDTLS_ERR_RSA_VERIFY_FAILED;
2158     }
2159 
2160     return 0;
2161 }
2162 
2163 /*
2164  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2165  */
2166 int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2167                                   mbedtls_md_type_t md_alg,
2168                                   unsigned int hashlen,
2169                                   const unsigned char *hash,
2170                                   const unsigned char *sig)
2171 {
2172     mbedtls_md_type_t mgf1_hash_id;
2173     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2174         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2175     }
2176 
2177     mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2178                              ? (mbedtls_md_type_t) ctx->hash_id
2179                              : md_alg;
2180 
2181     return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
2182                                              md_alg, hashlen, hash,
2183                                              mgf1_hash_id,
2184                                              MBEDTLS_RSA_SALT_LEN_ANY,
2185                                              sig);
2186 
2187 }
2188 #endif /* MBEDTLS_PKCS1_V21 */
2189 
2190 #if defined(MBEDTLS_PKCS1_V15)
2191 /*
2192  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2193  */
2194 int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
2195                                         mbedtls_md_type_t md_alg,
2196                                         unsigned int hashlen,
2197                                         const unsigned char *hash,
2198                                         const unsigned char *sig)
2199 {
2200     int ret = 0;
2201     size_t sig_len;
2202     unsigned char *encoded = NULL, *encoded_expected = NULL;
2203 
2204     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2205         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2206     }
2207 
2208     sig_len = ctx->len;
2209 
2210     /*
2211      * Prepare expected PKCS1 v1.5 encoding of hash.
2212      */
2213 
2214     if ((encoded          = mbedtls_calloc(1, sig_len)) == NULL ||
2215         (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2216         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2217         goto cleanup;
2218     }
2219 
2220     if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2221                                            encoded_expected)) != 0) {
2222         goto cleanup;
2223     }
2224 
2225     /*
2226      * Apply RSA primitive to get what should be PKCS1 encoded hash.
2227      */
2228 
2229     ret = mbedtls_rsa_public(ctx, sig, encoded);
2230     if (ret != 0) {
2231         goto cleanup;
2232     }
2233 
2234     /*
2235      * Compare
2236      */
2237 
2238     if ((ret = FTMN_CALLEE_DONE_MEMCMP(mbedtls_ct_memcmp, encoded,
2239                                        encoded_expected, sig_len )) != 0) {
2240         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2241         goto cleanup;
2242     }
2243 
2244 cleanup:
2245 
2246     if (encoded != NULL) {
2247         mbedtls_platform_zeroize(encoded, sig_len);
2248         mbedtls_free(encoded);
2249     }
2250 
2251     if (encoded_expected != NULL) {
2252         mbedtls_platform_zeroize(encoded_expected, sig_len);
2253         mbedtls_free(encoded_expected);
2254     }
2255 
2256     return ret;
2257 }
2258 #endif /* MBEDTLS_PKCS1_V15 */
2259 
2260 /*
2261  * Do an RSA operation and check the message digest
2262  */
2263 int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2264                              mbedtls_md_type_t md_alg,
2265                              unsigned int hashlen,
2266                              const unsigned char *hash,
2267                              const unsigned char *sig)
2268 {
2269     if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2270         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2271     }
2272 
2273     switch (ctx->padding) {
2274 #if defined(MBEDTLS_PKCS1_V15)
2275         case MBEDTLS_RSA_PKCS_V15:
2276             return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
2277                                                        hashlen, hash, sig);
2278 #endif
2279 
2280 #if defined(MBEDTLS_PKCS1_V21)
2281         case MBEDTLS_RSA_PKCS_V21:
2282             return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
2283                                                  hashlen, hash, sig);
2284 #endif
2285 
2286         default:
2287             return MBEDTLS_ERR_RSA_INVALID_PADDING;
2288     }
2289 }
2290 
2291 /*
2292  * Copy the components of an RSA key
2293  */
2294 int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2295 {
2296     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2297 
2298     dst->len = src->len;
2299 
2300     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2301     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2302 
2303     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2304     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2305     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2306 
2307 #if !defined(MBEDTLS_RSA_NO_CRT)
2308     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2309     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2310     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2311     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2312     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2313 #endif
2314 
2315     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2316 
2317     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2318     MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2319 
2320     dst->padding = src->padding;
2321     dst->hash_id = src->hash_id;
2322 
2323 cleanup:
2324     if (ret != 0) {
2325         mbedtls_rsa_free(dst);
2326     }
2327 
2328     return ret;
2329 }
2330 
2331 /*
2332  * Free the components of an RSA key
2333  */
2334 void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2335 {
2336     if (ctx == NULL) {
2337         return;
2338     }
2339 
2340     mbedtls_mpi_free(&ctx->Vi);
2341     mbedtls_mpi_free(&ctx->Vf);
2342     mbedtls_mpi_free(&ctx->RN);
2343     mbedtls_mpi_free(&ctx->D);
2344     mbedtls_mpi_free(&ctx->Q);
2345     mbedtls_mpi_free(&ctx->P);
2346     mbedtls_mpi_free(&ctx->E);
2347     mbedtls_mpi_free(&ctx->N);
2348 
2349 #if !defined(MBEDTLS_RSA_NO_CRT)
2350     mbedtls_mpi_free(&ctx->RQ);
2351     mbedtls_mpi_free(&ctx->RP);
2352     mbedtls_mpi_free(&ctx->QP);
2353     mbedtls_mpi_free(&ctx->DQ);
2354     mbedtls_mpi_free(&ctx->DP);
2355 #endif /* MBEDTLS_RSA_NO_CRT */
2356 
2357 #if defined(MBEDTLS_THREADING_C)
2358     /* Free the mutex, but only if it hasn't been freed already. */
2359     if (ctx->ver != 0) {
2360         mbedtls_mutex_free(&ctx->mutex);
2361         ctx->ver = 0;
2362     }
2363 #endif
2364 }
2365 
2366 #endif /* !MBEDTLS_RSA_ALT */
2367 
2368 #if defined(MBEDTLS_SELF_TEST)
2369 
2370 #include "mbedtls/md.h"
2371 
2372 /*
2373  * Example RSA-1024 keypair, for test purposes
2374  */
2375 #define KEY_LEN 128
2376 
2377 #define RSA_N   "9292758453063D803DD603D5E777D788" \
2378                 "8ED1D5BF35786190FA2F23EBC0848AEA" \
2379                 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2380                 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2381                 "93A89813FBF3C4F8066D2D800F7C38A8" \
2382                 "1AE31942917403FF4946B0A83D3D3E05" \
2383                 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2384                 "5E94BB77B07507233A0BC7BAC8F90F79"
2385 
2386 #define RSA_E   "10001"
2387 
2388 #define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
2389                 "66CA472BC44D253102F8B4A9D3BFA750" \
2390                 "91386C0077937FE33FA3252D28855837" \
2391                 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2392                 "DF79C5CE07EE72C7F123142198164234" \
2393                 "CABB724CF78B8173B9F880FC86322407" \
2394                 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2395                 "071513A1E85B5DFA031F21ECAE91A34D"
2396 
2397 #define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2398                 "2C01CAD19EA484A87EA4377637E75500" \
2399                 "FCB2005C5C7DD6EC4AC023CDA285D796" \
2400                 "C3D9E75E1EFC42488BB4F1D13AC30A57"
2401 
2402 #define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
2403                 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2404                 "910E4168387E3C30AA1E00C339A79508" \
2405                 "8452DD96A9A5EA5D9DCA68DA636032AF"
2406 
2407 #define PT_LEN  24
2408 #define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2409                 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2410 
2411 #if defined(MBEDTLS_PKCS1_V15)
2412 static int myrand(void *rng_state, unsigned char *output, size_t len)
2413 {
2414 #if !defined(__OpenBSD__) && !defined(__NetBSD__)
2415     size_t i;
2416 
2417     if (rng_state != NULL) {
2418         rng_state  = NULL;
2419     }
2420 
2421     for (i = 0; i < len; ++i) {
2422         output[i] = rand();
2423     }
2424 #else
2425     if (rng_state != NULL) {
2426         rng_state = NULL;
2427     }
2428 
2429     arc4random_buf(output, len);
2430 #endif /* !OpenBSD && !NetBSD */
2431 
2432     return 0;
2433 }
2434 #endif /* MBEDTLS_PKCS1_V15 */
2435 
2436 /*
2437  * Checkup routine
2438  */
2439 int mbedtls_rsa_self_test(int verbose)
2440 {
2441     int ret = 0;
2442 #if defined(MBEDTLS_PKCS1_V15)
2443     size_t len;
2444     mbedtls_rsa_context rsa;
2445     unsigned char rsa_plaintext[PT_LEN];
2446     unsigned char rsa_decrypted[PT_LEN];
2447     unsigned char rsa_ciphertext[KEY_LEN];
2448 #if defined(MBEDTLS_SHA1_C)
2449     unsigned char sha1sum[20];
2450 #endif
2451 
2452     mbedtls_mpi K;
2453 
2454     mbedtls_mpi_init(&K);
2455     mbedtls_rsa_init(&rsa);
2456 
2457     MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2458     MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2459     MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2460     MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2461     MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2462     MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2463     MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2464     MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2465     MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2466     MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2467 
2468     MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2469 
2470     if (verbose != 0) {
2471         mbedtls_printf("  RSA key validation: ");
2472     }
2473 
2474     if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2475         mbedtls_rsa_check_privkey(&rsa) != 0) {
2476         if (verbose != 0) {
2477             mbedtls_printf("failed\n");
2478         }
2479 
2480         ret = 1;
2481         goto cleanup;
2482     }
2483 
2484     if (verbose != 0) {
2485         mbedtls_printf("passed\n  PKCS#1 encryption : ");
2486     }
2487 
2488     memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2489 
2490     if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
2491                                   PT_LEN, rsa_plaintext,
2492                                   rsa_ciphertext) != 0) {
2493         if (verbose != 0) {
2494             mbedtls_printf("failed\n");
2495         }
2496 
2497         ret = 1;
2498         goto cleanup;
2499     }
2500 
2501     if (verbose != 0) {
2502         mbedtls_printf("passed\n  PKCS#1 decryption : ");
2503     }
2504 
2505     if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
2506                                   &len, rsa_ciphertext, rsa_decrypted,
2507                                   sizeof(rsa_decrypted)) != 0) {
2508         if (verbose != 0) {
2509             mbedtls_printf("failed\n");
2510         }
2511 
2512         ret = 1;
2513         goto cleanup;
2514     }
2515 
2516     if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
2517         if (verbose != 0) {
2518             mbedtls_printf("failed\n");
2519         }
2520 
2521         ret = 1;
2522         goto cleanup;
2523     }
2524 
2525     if (verbose != 0) {
2526         mbedtls_printf("passed\n");
2527     }
2528 
2529 #if defined(MBEDTLS_SHA1_C)
2530     if (verbose != 0) {
2531         mbedtls_printf("  PKCS#1 data sign  : ");
2532     }
2533 
2534     if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
2535                    rsa_plaintext, PT_LEN, sha1sum) != 0) {
2536         if (verbose != 0) {
2537             mbedtls_printf("failed\n");
2538         }
2539 
2540         return 1;
2541     }
2542 
2543     if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
2544                                MBEDTLS_MD_SHA1, 20,
2545                                sha1sum, rsa_ciphertext) != 0) {
2546         if (verbose != 0) {
2547             mbedtls_printf("failed\n");
2548         }
2549 
2550         ret = 1;
2551         goto cleanup;
2552     }
2553 
2554     if (verbose != 0) {
2555         mbedtls_printf("passed\n  PKCS#1 sig. verify: ");
2556     }
2557 
2558     if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
2559                                  sha1sum, rsa_ciphertext) != 0) {
2560         if (verbose != 0) {
2561             mbedtls_printf("failed\n");
2562         }
2563 
2564         ret = 1;
2565         goto cleanup;
2566     }
2567 
2568     if (verbose != 0) {
2569         mbedtls_printf("passed\n");
2570     }
2571 #endif /* MBEDTLS_SHA1_C */
2572 
2573     if (verbose != 0) {
2574         mbedtls_printf("\n");
2575     }
2576 
2577 cleanup:
2578     mbedtls_mpi_free(&K);
2579     mbedtls_rsa_free(&rsa);
2580 #else /* MBEDTLS_PKCS1_V15 */
2581     ((void) verbose);
2582 #endif /* MBEDTLS_PKCS1_V15 */
2583     return ret;
2584 }
2585 
2586 #endif /* MBEDTLS_SELF_TEST */
2587 
2588 #endif /* MBEDTLS_RSA_C */
2589