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