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