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