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