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