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