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