2 * The RSA public-key cryptosystem
4 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5 * SPDX-License-Identifier: GPL-2.0
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.
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.
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.
21 * This file is part of mbed TLS (https://tls.mbed.org)
25 * The following sources were referenced in the design of this implementation
26 * of the RSA algorithm:
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
32 * [2] Handbook of Applied Cryptography - 1997, Chapter 8
33 * Menezes, van Oorschot and Vanstone
35 * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
36 * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
38 * https://arxiv.org/abs/1702.08719v2
42 #if !defined(MBEDTLS_CONFIG_FILE)
43 #include "mbedtls/config.h"
45 #include MBEDTLS_CONFIG_FILE
48 #if defined(MBEDTLS_RSA_C)
50 #include "mbedtls/rsa.h"
51 #include "mbedtls/rsa_internal.h"
52 #include "mbedtls/oid.h"
56 #if defined(MBEDTLS_PKCS1_V21)
57 #include "mbedtls/md.h"
60 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)
64 #if defined(MBEDTLS_PLATFORM_C)
65 #include "mbedtls/platform.h"
68 #define mbedtls_printf printf
69 #define mbedtls_calloc calloc
70 #define mbedtls_free free
73 #if !defined(MBEDTLS_RSA_ALT)
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;
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
)
85 const unsigned char *A
= (const unsigned char *) a
;
86 const unsigned char *B
= (const unsigned char *) b
;
87 unsigned char diff
= 0;
89 for( i
= 0; i
< n
; i
++ )
94 #endif /* MBEDTLS_PKCS1_V15 */
96 int mbedtls_rsa_import( mbedtls_rsa_context
*ctx
,
98 const mbedtls_mpi
*P
, const mbedtls_mpi
*Q
,
99 const mbedtls_mpi
*D
, const mbedtls_mpi
*E
)
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 ) )
109 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
113 ctx
->len
= mbedtls_mpi_size( &ctx
->N
);
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
)
129 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx
->N
, N
, N_len
) );
130 ctx
->len
= mbedtls_mpi_size( &ctx
->N
);
134 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx
->P
, P
, P_len
) );
137 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx
->Q
, Q
, Q_len
) );
140 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx
->D
, D
, D_len
) );
143 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx
->E
, E
, E_len
) );
148 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
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.
158 static int rsa_check_context( mbedtls_rsa_context
const *ctx
, int is_priv
,
159 int blinding_needed
)
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
);
167 if( ctx
->len
!= mbedtls_mpi_size( &ctx
->N
) ||
168 ctx
->len
> MBEDTLS_MPI_MAX_SIZE
)
170 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
174 * 1. Modular exponentiation needs positive, odd moduli.
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 )
182 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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
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 ) )
195 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
197 #endif /* !MBEDTLS_RSA_NO_CRT */
200 * 2. Exponents must be positive
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
);
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
);
214 ( mbedtls_mpi_cmp_int( &ctx
->DP
, 0 ) <= 0 ||
215 mbedtls_mpi_cmp_int( &ctx
->DQ
, 0 ) <= 0 ) )
217 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
219 #endif /* MBEDTLS_RSA_NO_CRT */
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 ) )
229 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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)
237 mbedtls_mpi_cmp_int( &ctx
->QP
, 0 ) <= 0 )
239 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
246 int mbedtls_rsa_complete( mbedtls_rsa_context
*ctx
)
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 );
257 * Check whether provided parameters are enough
258 * to deduce all others. The following incomplete
259 * parameter sets for private keys are supported:
262 * (2) D and potentially N missing.
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
;
271 /* These three alternatives are mutually exclusive */
272 const int is_priv
= n_missing
|| pq_missing
|| d_missing
;
274 if( !is_priv
&& !is_pub
)
275 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
278 * Step 1: Deduce N if P, Q are provided.
281 if( !have_N
&& have_P
&& have_Q
)
283 if( ( ret
= mbedtls_mpi_mul_mpi( &ctx
->N
, &ctx
->P
,
286 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
289 ctx
->len
= mbedtls_mpi_size( &ctx
->N
);
293 * Step 2: Deduce and verify all remaining core parameters.
298 ret
= mbedtls_rsa_deduce_primes( &ctx
->N
, &ctx
->E
, &ctx
->D
,
301 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
306 if( ( ret
= mbedtls_rsa_deduce_private_exponent( &ctx
->P
,
311 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
316 * Step 3: Deduce all additional parameters specific
317 * to our current RSA implementation.
320 #if !defined(MBEDTLS_RSA_NO_CRT)
323 ret
= mbedtls_rsa_deduce_crt( &ctx
->P
, &ctx
->Q
, &ctx
->D
,
324 &ctx
->DP
, &ctx
->DQ
, &ctx
->QP
);
326 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
328 #endif /* MBEDTLS_RSA_NO_CRT */
331 * Step 3: Basic sanity checks
334 return( rsa_check_context( ctx
, is_priv
, 1 ) );
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
)
346 /* Check if key is private or public */
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;
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
);
364 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx
->N
, N
, N_len
) );
367 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx
->P
, P
, P_len
) );
370 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx
->Q
, Q
, Q_len
) );
373 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx
->D
, D
, D_len
) );
376 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx
->E
, E
, E_len
) );
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
)
389 /* Check if key is private or public */
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;
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
);
406 /* Export all requested core parameters. */
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 ) )
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.
426 int mbedtls_rsa_export_crt( const mbedtls_rsa_context
*ctx
,
427 mbedtls_mpi
*DP
, mbedtls_mpi
*DQ
, mbedtls_mpi
*QP
)
431 /* Check if key is private or public */
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;
440 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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 ) )
448 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
451 if( ( ret
= mbedtls_rsa_deduce_crt( &ctx
->P
, &ctx
->Q
, &ctx
->D
,
452 DP
, DQ
, QP
) ) != 0 )
454 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
+ ret
);
462 * Initialize an RSA context
464 void mbedtls_rsa_init( mbedtls_rsa_context
*ctx
,
468 memset( ctx
, 0, sizeof( mbedtls_rsa_context
) );
470 mbedtls_rsa_set_padding( ctx
, padding
, hash_id
);
472 #if defined(MBEDTLS_THREADING_C)
473 mbedtls_mutex_init( &ctx
->mutex
);
478 * Set padding for an existing RSA context
480 void mbedtls_rsa_set_padding( mbedtls_rsa_context
*ctx
, int padding
, int hash_id
)
482 ctx
->padding
= padding
;
483 ctx
->hash_id
= hash_id
;
487 * Get length in bytes of RSA modulus
490 size_t mbedtls_rsa_get_len( const mbedtls_rsa_context
*ctx
)
496 #if defined(MBEDTLS_GENPRIME)
499 * Generate an RSA keypair
501 int mbedtls_rsa_gen_key( mbedtls_rsa_context
*ctx
,
502 int (*f_rng
)(void *, unsigned char *, size_t),
504 unsigned int nbits
, int exponent
)
509 if( f_rng
== NULL
|| nbits
< 128 || exponent
< 3 )
510 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
513 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
515 mbedtls_mpi_init( &H
);
516 mbedtls_mpi_init( &G
);
519 * find primes P and Q with Q < P so that:
520 * GCD( E, (P-1)*(Q-1) ) == 1
522 MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx
->E
, exponent
) );
526 MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx
->P
, nbits
>> 1, 0,
529 MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx
->Q
, nbits
>> 1, 0,
532 if( mbedtls_mpi_cmp_mpi( &ctx
->P
, &ctx
->Q
) == 0 )
535 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx
->N
, &ctx
->P
, &ctx
->Q
) );
536 if( mbedtls_mpi_bitlen( &ctx
->N
) != nbits
)
539 if( mbedtls_mpi_cmp_mpi( &ctx
->P
, &ctx
->Q
) < 0 )
540 mbedtls_mpi_swap( &ctx
->P
, &ctx
->Q
);
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
) );
548 while( mbedtls_mpi_cmp_int( &G
, 1 ) != 0 );
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 ) );
554 ctx
->len
= mbedtls_mpi_size( &ctx
->N
);
557 * D = E^-1 mod ((P-1)*(Q-1))
563 MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx
->D
, &ctx
->E
, &H
) );
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 */
571 MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx
) );
575 mbedtls_mpi_free( &H
);
576 mbedtls_mpi_free( &G
);
580 mbedtls_rsa_free( ctx
);
581 return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED
+ ret
);
587 #endif /* MBEDTLS_GENPRIME */
590 * Check a public RSA key
592 int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context
*ctx
)
594 if( rsa_check_context( ctx
, 0 /* public */, 0 /* no blinding */ ) != 0 )
595 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
597 if( mbedtls_mpi_bitlen( &ctx
->N
) < 128 )
599 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
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 )
606 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
613 * Check for the consistency of all fields in an RSA private key context
615 int mbedtls_rsa_check_privkey( const mbedtls_rsa_context
*ctx
)
617 if( mbedtls_rsa_check_pubkey( ctx
) != 0 ||
618 rsa_check_context( ctx
, 1 /* private */, 1 /* blinding */ ) != 0 )
620 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
623 if( mbedtls_rsa_validate_params( &ctx
->N
, &ctx
->P
, &ctx
->Q
,
624 &ctx
->D
, &ctx
->E
, NULL
, NULL
) != 0 )
626 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
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 )
633 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
641 * Check if contexts holding a public and private key match
643 int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context
*pub
,
644 const mbedtls_rsa_context
*prv
)
646 if( mbedtls_rsa_check_pubkey( pub
) != 0 ||
647 mbedtls_rsa_check_privkey( prv
) != 0 )
649 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
652 if( mbedtls_mpi_cmp_mpi( &pub
->N
, &prv
->N
) != 0 ||
653 mbedtls_mpi_cmp_mpi( &pub
->E
, &prv
->E
) != 0 )
655 return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED
);
662 * Do an RSA public key operation
664 int mbedtls_rsa_public( mbedtls_rsa_context
*ctx
,
665 const unsigned char *input
,
666 unsigned char *output
)
672 if( rsa_check_context( ctx
, 0 /* public */, 0 /* no blinding */ ) )
673 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
675 mbedtls_mpi_init( &T
);
677 #if defined(MBEDTLS_THREADING_C)
678 if( ( ret
= mbedtls_mutex_lock( &ctx
->mutex
) ) != 0 )
682 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T
, input
, ctx
->len
) );
684 if( mbedtls_mpi_cmp_mpi( &T
, &ctx
->N
) >= 0 )
686 ret
= MBEDTLS_ERR_MPI_BAD_INPUT_DATA
;
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
) );
695 #if defined(MBEDTLS_THREADING_C)
696 if( mbedtls_mutex_unlock( &ctx
->mutex
) != 0 )
697 return( MBEDTLS_ERR_THREADING_MUTEX_ERROR
);
700 mbedtls_mpi_free( &T
);
703 return( MBEDTLS_ERR_RSA_PUBLIC_FAILED
+ ret
);
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.
714 static int rsa_prepare_blinding( mbedtls_rsa_context
*ctx
,
715 int (*f_rng
)(void *, unsigned char *, size_t), void *p_rng
)
719 if( ctx
->Vf
.p
!= NULL
)
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
) );
730 /* Unblinding value: Vf = random number, invertible mod N */
733 return( MBEDTLS_ERR_RSA_RNG_FAILED
);
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 );
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
) );
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].
753 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
754 * observations on avarage.
756 * For example with 28 byte blinding to achieve 2 collisions the adversary has
757 * to make 2^112 observations on avarage.
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])
764 * This countermeasure does not help if the key recovery is possible with a
767 #define RSA_EXPONENT_BLINDING 28
770 * Do an RSA private key operation
772 int mbedtls_rsa_private( mbedtls_rsa_context
*ctx
,
773 int (*f_rng
)(void *, unsigned char *, size_t),
775 const unsigned char *input
,
776 unsigned char *output
)
781 /* Temporary holding the result */
784 /* Temporaries holding P-1, Q-1 and the
785 * exponent blinding factor, respectively. */
786 mbedtls_mpi P1
, Q1
, R
;
788 #if !defined(MBEDTLS_RSA_NO_CRT)
789 /* Temporaries holding the results mod p resp. mod q. */
792 /* Temporaries holding the blinded exponents for
793 * the mod p resp. mod q computation (if used). */
794 mbedtls_mpi DP_blind
, DQ_blind
;
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
;
801 /* Temporary holding the blinded exponent (if used). */
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 */
809 /* Temporaries holding the initial input and the double
810 * checked result; should be the same in the end. */
813 if( rsa_check_context( ctx
, 1 /* private key checks */,
814 f_rng
!= NULL
/* blinding y/n */ ) != 0 )
816 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
819 #if defined(MBEDTLS_THREADING_C)
820 if( ( ret
= mbedtls_mutex_lock( &ctx
->mutex
) ) != 0 )
824 /* MPI Initialization */
825 mbedtls_mpi_init( &T
);
827 mbedtls_mpi_init( &P1
);
828 mbedtls_mpi_init( &Q1
);
829 mbedtls_mpi_init( &R
);
833 #if defined(MBEDTLS_RSA_NO_CRT)
834 mbedtls_mpi_init( &D_blind
);
836 mbedtls_mpi_init( &DP_blind
);
837 mbedtls_mpi_init( &DQ_blind
);
841 #if !defined(MBEDTLS_RSA_NO_CRT)
842 mbedtls_mpi_init( &TP
); mbedtls_mpi_init( &TQ
);
845 mbedtls_mpi_init( &I
);
846 mbedtls_mpi_init( &C
);
848 /* End of MPI initialization */
850 MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T
, input
, ctx
->len
) );
851 if( mbedtls_mpi_cmp_mpi( &T
, &ctx
->N
) >= 0 )
853 ret
= MBEDTLS_ERR_MPI_BAD_INPUT_DATA
;
857 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I
, &T
) );
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
) );
872 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1
, &ctx
->P
, 1 ) );
873 MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1
, &ctx
->Q
, 1 ) );
875 #if defined(MBEDTLS_RSA_NO_CRT)
877 * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
879 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R
, RSA_EXPONENT_BLINDING
,
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
) );
888 * DP_blind = ( P - 1 ) * R + DP
890 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R
, RSA_EXPONENT_BLINDING
,
892 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind
, &P1
, &R
) );
893 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind
, &DP_blind
,
899 * DQ_blind = ( Q - 1 ) * R + DQ
901 MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R
, RSA_EXPONENT_BLINDING
,
903 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind
, &Q1
, &R
) );
904 MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind
, &DQ_blind
,
908 #endif /* MBEDTLS_RSA_NO_CRT */
911 #if defined(MBEDTLS_RSA_NO_CRT)
912 MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T
, &T
, D
, &ctx
->N
, &ctx
->RN
) );
915 * Faster decryption using the CRT
917 * TP = input ^ dP mod P
918 * TQ = input ^ dQ mod Q
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
) );
925 * T = (TP - TQ) * (Q^-1 mod P) mod P
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
) );
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 */
944 MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T
, &T
, &ctx
->Vf
) );
945 MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T
, &T
, &ctx
->N
) );
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 )
953 ret
= MBEDTLS_ERR_RSA_VERIFY_FAILED
;
958 MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T
, output
, olen
) );
961 #if defined(MBEDTLS_THREADING_C)
962 if( mbedtls_mutex_unlock( &ctx
->mutex
) != 0 )
963 return( MBEDTLS_ERR_THREADING_MUTEX_ERROR
);
966 mbedtls_mpi_free( &P1
);
967 mbedtls_mpi_free( &Q1
);
968 mbedtls_mpi_free( &R
);
972 #if defined(MBEDTLS_RSA_NO_CRT)
973 mbedtls_mpi_free( &D_blind
);
975 mbedtls_mpi_free( &DP_blind
);
976 mbedtls_mpi_free( &DQ_blind
);
980 mbedtls_mpi_free( &T
);
982 #if !defined(MBEDTLS_RSA_NO_CRT)
983 mbedtls_mpi_free( &TP
); mbedtls_mpi_free( &TQ
);
986 mbedtls_mpi_free( &C
);
987 mbedtls_mpi_free( &I
);
990 return( MBEDTLS_ERR_RSA_PRIVATE_FAILED
+ ret
);
995 #if defined(MBEDTLS_PKCS1_V21)
997 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
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
1005 static int mgf_mask( unsigned char *dst
, size_t dlen
, unsigned char *src
,
1006 size_t slen
, mbedtls_md_context_t
*md_ctx
)
1008 unsigned char mask
[MBEDTLS_MD_MAX_SIZE
];
1009 unsigned char counter
[4];
1015 memset( mask
, 0, MBEDTLS_MD_MAX_SIZE
);
1016 memset( counter
, 0, 4 );
1018 hlen
= mbedtls_md_get_size( md_ctx
->md_info
);
1020 /* Generate and apply dbMask */
1029 if( ( ret
= mbedtls_md_starts( md_ctx
) ) != 0 )
1031 if( ( ret
= mbedtls_md_update( md_ctx
, src
, slen
) ) != 0 )
1033 if( ( ret
= mbedtls_md_update( md_ctx
, counter
, 4 ) ) != 0 )
1035 if( ( ret
= mbedtls_md_finish( md_ctx
, mask
) ) != 0 )
1038 for( i
= 0; i
< use_len
; ++i
)
1047 mbedtls_zeroize( mask
, sizeof( mask
) );
1051 #endif /* MBEDTLS_PKCS1_V21 */
1053 #if defined(MBEDTLS_PKCS1_V21)
1055 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1057 int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context
*ctx
,
1058 int (*f_rng
)(void *, unsigned char *, size_t),
1061 const unsigned char *label
, size_t label_len
,
1063 const unsigned char *input
,
1064 unsigned char *output
)
1068 unsigned char *p
= output
;
1070 const mbedtls_md_info_t
*md_info
;
1071 mbedtls_md_context_t md_ctx
;
1073 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V21
)
1074 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1077 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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
);
1084 hlen
= mbedtls_md_get_size( md_info
);
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
);
1090 memset( output
, 0, olen
);
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
);
1101 if( ( ret
= mbedtls_md( md_info
, label
, label_len
, p
) ) != 0 )
1104 p
+= olen
- 2 * hlen
- 2 - ilen
;
1106 memcpy( p
, input
, ilen
);
1108 mbedtls_md_init( &md_ctx
);
1109 if( ( ret
= mbedtls_md_setup( &md_ctx
, md_info
, 0 ) ) != 0 )
1112 /* maskedDB: Apply dbMask to DB */
1113 if( ( ret
= mgf_mask( output
+ hlen
+ 1, olen
- hlen
- 1, output
+ 1, hlen
,
1117 /* maskedSeed: Apply seedMask to seed */
1118 if( ( ret
= mgf_mask( output
+ 1, hlen
, output
+ hlen
+ 1, olen
- hlen
- 1,
1123 mbedtls_md_free( &md_ctx
);
1128 return( ( mode
== MBEDTLS_RSA_PUBLIC
)
1129 ? mbedtls_rsa_public( ctx
, output
, output
)
1130 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, output
, output
) );
1132 #endif /* MBEDTLS_PKCS1_V21 */
1134 #if defined(MBEDTLS_PKCS1_V15)
1136 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1138 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context
*ctx
,
1139 int (*f_rng
)(void *, unsigned char *, size_t),
1141 int mode
, size_t ilen
,
1142 const unsigned char *input
,
1143 unsigned char *output
)
1145 size_t nb_pad
, olen
;
1147 unsigned char *p
= output
;
1149 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V15
)
1150 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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
);
1158 /* first comparison checks for overflow */
1159 if( ilen
+ 11 < ilen
|| olen
< ilen
+ 11 )
1160 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1162 nb_pad
= olen
- 3 - ilen
;
1165 if( mode
== MBEDTLS_RSA_PUBLIC
)
1167 *p
++ = MBEDTLS_RSA_CRYPT
;
1169 while( nb_pad
-- > 0 )
1174 ret
= f_rng( p_rng
, p
, 1 );
1175 } while( *p
== 0 && --rng_dl
&& ret
== 0 );
1177 /* Check if RNG failed to generate data */
1178 if( rng_dl
== 0 || ret
!= 0 )
1179 return( MBEDTLS_ERR_RSA_RNG_FAILED
+ ret
);
1186 *p
++ = MBEDTLS_RSA_SIGN
;
1188 while( nb_pad
-- > 0 )
1193 memcpy( p
, input
, ilen
);
1195 return( ( mode
== MBEDTLS_RSA_PUBLIC
)
1196 ? mbedtls_rsa_public( ctx
, output
, output
)
1197 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, output
, output
) );
1199 #endif /* MBEDTLS_PKCS1_V15 */
1202 * Add the message padding, then do an RSA operation
1204 int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context
*ctx
,
1205 int (*f_rng
)(void *, unsigned char *, size_t),
1207 int mode
, size_t ilen
,
1208 const unsigned char *input
,
1209 unsigned char *output
)
1211 switch( ctx
->padding
)
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
,
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
);
1226 return( MBEDTLS_ERR_RSA_INVALID_PADDING
);
1230 #if defined(MBEDTLS_PKCS1_V21)
1232 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1234 int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context
*ctx
,
1235 int (*f_rng
)(void *, unsigned char *, size_t),
1238 const unsigned char *label
, size_t label_len
,
1240 const unsigned char *input
,
1241 unsigned char *output
,
1242 size_t output_max_len
)
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
];
1250 const mbedtls_md_info_t
*md_info
;
1251 mbedtls_md_context_t md_ctx
;
1254 * Parameters sanity checks
1256 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V21
)
1257 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1261 if( ilen
< 16 || ilen
> sizeof( buf
) )
1262 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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
);
1268 hlen
= mbedtls_md_get_size( md_info
);
1270 // checking for integer underflow
1271 if( 2 * hlen
+ 2 > ilen
)
1272 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1277 ret
= ( mode
== MBEDTLS_RSA_PUBLIC
)
1278 ? mbedtls_rsa_public( ctx
, input
, buf
)
1279 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, input
, buf
);
1285 * Unmask data and generate lHash
1287 mbedtls_md_init( &md_ctx
);
1288 if( ( ret
= mbedtls_md_setup( &md_ctx
, md_info
, 0 ) ) != 0 )
1290 mbedtls_md_free( &md_ctx
);
1294 /* seed: Apply seedMask to maskedSeed */
1295 if( ( ret
= mgf_mask( buf
+ 1, hlen
, buf
+ hlen
+ 1, ilen
- hlen
- 1,
1297 /* DB: Apply dbMask to maskedDB */
1298 ( ret
= mgf_mask( buf
+ hlen
+ 1, ilen
- hlen
- 1, buf
+ 1, hlen
,
1301 mbedtls_md_free( &md_ctx
);
1305 mbedtls_md_free( &md_ctx
);
1307 /* Generate lHash */
1308 if( ( ret
= mbedtls_md( md_info
, label
, label_len
, lhash
) ) != 0 )
1312 * Check contents, in "constant-time"
1317 bad
|= *p
++; /* First byte must be 0 */
1319 p
+= hlen
; /* Skip seed */
1322 for( i
= 0; i
< hlen
; i
++ )
1323 bad
|= lhash
[i
] ^ *p
++;
1325 /* Get zero-padding len, but always read till end of buffer
1326 * (minus one, for the 01 byte) */
1329 for( i
= 0; i
< ilen
- 2 * hlen
- 2; i
++ )
1332 pad_len
+= ((pad_done
| (unsigned char)-pad_done
) >> 7) ^ 1;
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.
1346 ret
= MBEDTLS_ERR_RSA_INVALID_PADDING
;
1350 if( ilen
- ( p
- buf
) > output_max_len
)
1352 ret
= MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE
;
1356 *olen
= ilen
- (p
- buf
);
1357 memcpy( output
, p
, *olen
);
1361 mbedtls_zeroize( buf
, sizeof( buf
) );
1362 mbedtls_zeroize( lhash
, sizeof( lhash
) );
1366 #endif /* MBEDTLS_PKCS1_V21 */
1368 #if defined(MBEDTLS_PKCS1_V15)
1369 /** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
1371 * \param value The value to analyze.
1372 * \return Zero if \p value is zero, otherwise all-bits-one.
1374 static unsigned all_or_nothing_int( unsigned value
)
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 )
1382 return( - ( ( value
| - value
) >> ( sizeof( value
) * 8 - 1 ) ) );
1383 #if defined(_MSC_VER)
1384 #pragma warning( pop )
1388 /** Check whether a size is out of bounds, without branches.
1390 * This is equivalent to `size > max`, but is likely to be compiled to
1391 * to code using bitwise operation rather than a branch.
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`.
1398 static unsigned size_greater_than( size_t size
, size_t max
)
1400 /* Return the sign bit (1 for negative) of (max - size). */
1401 return( ( max
- size
) >> ( sizeof( size_t ) * 8 - 1 ) );
1404 /** Choose between two integer values, without branches.
1406 * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled
1407 * to code using bitwise operation rather than a branch.
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.
1414 static unsigned if_int( unsigned cond
, unsigned if1
, unsigned if0
)
1416 unsigned mask
= all_or_nothing_int( cond
);
1417 return( ( mask
& if1
) | (~mask
& if0
) );
1420 /** Shift some data towards the left inside a buffer without leaking
1421 * the length of the data through side channels.
1423 * `mem_move_to_left(start, total, offset)` is functionally equivalent to
1425 * memmove(start, start + offset, total - offset);
1426 * memset(start + offset, 0, total - offset);
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.
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.
1436 static void mem_move_to_left( void *start
,
1440 volatile unsigned char *buf
= start
;
1444 for( i
= 0; i
< total
; i
++ )
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
++ )
1452 unsigned char current
= buf
[n
];
1453 unsigned char next
= buf
[n
+1];
1454 buf
[n
] = if_int( no_op
, current
, next
);
1456 buf
[total
-1] = if_int( no_op
, buf
[total
-1], 0 );
1461 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
1463 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context
*ctx
,
1464 int (*f_rng
)(void *, unsigned char *, size_t),
1466 int mode
, size_t *olen
,
1467 const unsigned char *input
,
1468 unsigned char *output
,
1469 size_t output_max_len
)
1472 size_t ilen
= ctx
->len
;
1474 size_t plaintext_max_size
= ( output_max_len
> ilen
- 11 ?
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;
1490 unsigned char pad_done
= 0;
1491 size_t plaintext_size
= 0;
1492 unsigned output_too_large
;
1494 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V15
)
1495 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1497 if( ilen
< 16 || ilen
> sizeof( buf
) )
1498 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1500 ret
= ( mode
== MBEDTLS_RSA_PUBLIC
)
1501 ? mbedtls_rsa_public( ctx
, input
, buf
)
1502 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, input
, buf
);
1507 /* Check and get padding length in constant time and constant
1508 * memory trace. The first byte must be 0. */
1511 if( mode
== MBEDTLS_RSA_PRIVATE
)
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
;
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
++ )
1521 pad_done
|= ((buf
[i
] | (unsigned char)-buf
[i
]) >> 7) ^ 1;
1522 pad_count
+= ((pad_done
| (unsigned char)-pad_done
) >> 7) ^ 1;
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
;
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
++ )
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 );
1542 /* If pad_done is still zero, there's no data, only unfinished padding. */
1543 bad
|= if_int( pad_done
, 0, 1 );
1545 /* There must be at least 8 bytes of padding. */
1546 bad
|= size_greater_than( 8, pad_count
);
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 ) );
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
);
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
,
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
++ )
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
);
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
1597 mem_move_to_left( buf
+ ilen
- plaintext_max_size
,
1599 plaintext_max_size
- plaintext_size
);
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
);
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
;
1612 mbedtls_zeroize( buf
, sizeof( buf
) );
1616 #endif /* MBEDTLS_PKCS1_V15 */
1619 * Do an RSA operation, then remove the message padding
1621 int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context
*ctx
,
1622 int (*f_rng
)(void *, unsigned char *, size_t),
1624 int mode
, size_t *olen
,
1625 const unsigned char *input
,
1626 unsigned char *output
,
1627 size_t output_max_len
)
1629 switch( ctx
->padding
)
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
);
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
,
1645 return( MBEDTLS_ERR_RSA_INVALID_PADDING
);
1649 #if defined(MBEDTLS_PKCS1_V21)
1651 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
1653 int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context
*ctx
,
1654 int (*f_rng
)(void *, unsigned char *, size_t),
1657 mbedtls_md_type_t md_alg
,
1658 unsigned int hashlen
,
1659 const unsigned char *hash
,
1660 unsigned char *sig
)
1663 unsigned char *p
= sig
;
1664 unsigned char salt
[MBEDTLS_MD_MAX_SIZE
];
1665 unsigned int slen
, hlen
, offset
= 0;
1668 const mbedtls_md_info_t
*md_info
;
1669 mbedtls_md_context_t md_ctx
;
1671 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V21
)
1672 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1675 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1679 if( md_alg
!= MBEDTLS_MD_NONE
)
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
);
1686 hashlen
= mbedtls_md_get_size( md_info
);
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
);
1693 hlen
= mbedtls_md_get_size( md_info
);
1696 if( olen
< hlen
+ slen
+ 2 )
1697 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1699 memset( sig
, 0, olen
);
1701 /* Generate salt of length slen */
1702 if( ( ret
= f_rng( p_rng
, salt
, slen
) ) != 0 )
1703 return( MBEDTLS_ERR_RSA_RNG_FAILED
+ ret
);
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;
1709 memcpy( p
, salt
, slen
);
1712 mbedtls_md_init( &md_ctx
);
1713 if( ( ret
= mbedtls_md_setup( &md_ctx
, md_info
, 0 ) ) != 0 )
1716 /* Generate H = Hash( M' ) */
1717 if( ( ret
= mbedtls_md_starts( &md_ctx
) ) != 0 )
1719 if( ( ret
= mbedtls_md_update( &md_ctx
, p
, 8 ) ) != 0 )
1721 if( ( ret
= mbedtls_md_update( &md_ctx
, hash
, hashlen
) ) != 0 )
1723 if( ( ret
= mbedtls_md_update( &md_ctx
, salt
, slen
) ) != 0 )
1725 if( ( ret
= mbedtls_md_finish( &md_ctx
, p
) ) != 0 )
1728 /* Compensate for boundary condition when applying mask */
1732 /* maskedDB: Apply dbMask to DB */
1733 if( ( ret
= mgf_mask( sig
+ offset
, olen
- hlen
- 1 - offset
, p
, hlen
,
1737 msb
= mbedtls_mpi_bitlen( &ctx
->N
) - 1;
1738 sig
[0] &= 0xFF >> ( olen
* 8 - msb
);
1743 mbedtls_zeroize( salt
, sizeof( salt
) );
1746 mbedtls_md_free( &md_ctx
);
1751 return( ( mode
== MBEDTLS_RSA_PUBLIC
)
1752 ? mbedtls_rsa_public( ctx
, sig
, sig
)
1753 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, sig
, sig
) );
1755 #endif /* MBEDTLS_PKCS1_V21 */
1757 #if defined(MBEDTLS_PKCS1_V15)
1759 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
1762 /* Construct a PKCS v1.5 encoding of a hashed message
1764 * This is used both for signature generation and verification.
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.
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.
1780 static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg
,
1781 unsigned int hashlen
,
1782 const unsigned char *hash
,
1784 unsigned char *dst
)
1786 size_t oid_size
= 0;
1787 size_t nb_pad
= dst_len
;
1788 unsigned char *p
= dst
;
1789 const char *oid
= NULL
;
1791 /* Are we signing hashed or raw data? */
1792 if( md_alg
!= MBEDTLS_MD_NONE
)
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
);
1798 if( mbedtls_oid_get_oid_by_md( md_alg
, &oid
, &oid_size
) != 0 )
1799 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1801 hashlen
= mbedtls_md_get_size( md_info
);
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
);
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.
1818 if( nb_pad
< 10 + hashlen
+ oid_size
)
1819 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1820 nb_pad
-= 10 + hashlen
+ oid_size
;
1824 if( nb_pad
< hashlen
)
1825 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
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
);
1836 /* Now nb_pad is the amount of memory to be filled
1837 * with padding, and at least 8 bytes long. */
1839 /* Write signature header and padding */
1841 *p
++ = MBEDTLS_RSA_SIGN
;
1842 memset( p
, 0xFF, nb_pad
);
1846 /* Are we signing raw data? */
1847 if( md_alg
== MBEDTLS_MD_NONE
)
1849 memcpy( p
, hash
, hashlen
);
1853 /* Signing hashed data, add corresponding ASN.1 structure
1855 * DigestInfo ::= SEQUENCE {
1856 * digestAlgorithm DigestAlgorithmIdentifier,
1858 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1859 * Digest ::= OCTET STRING
1862 * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
1863 * TAG-NULL + LEN [ NULL ] ]
1864 * TAG-OCTET + LEN [ HASH ] ]
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
);
1874 *p
++ = MBEDTLS_ASN1_NULL
;
1876 *p
++ = MBEDTLS_ASN1_OCTET_STRING
;
1877 *p
++ = (unsigned char) hashlen
;
1878 memcpy( p
, hash
, hashlen
);
1881 /* Just a sanity-check, should be automatic
1882 * after the initial bounds check. */
1883 if( p
!= dst
+ dst_len
)
1885 mbedtls_zeroize( dst
, dst_len
);
1886 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1893 * Do an RSA operation to sign the message digest
1895 int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context
*ctx
,
1896 int (*f_rng
)(void *, unsigned char *, size_t),
1899 mbedtls_md_type_t md_alg
,
1900 unsigned int hashlen
,
1901 const unsigned char *hash
,
1902 unsigned char *sig
)
1905 unsigned char *sig_try
= NULL
, *verif
= NULL
;
1907 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V15
)
1908 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
1911 * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
1914 if( ( ret
= rsa_rsassa_pkcs1_v15_encode( md_alg
, hashlen
, hash
,
1915 ctx
->len
, sig
) ) != 0 )
1919 * Call respective RSA primitive
1922 if( mode
== MBEDTLS_RSA_PUBLIC
)
1924 /* Skip verification on a public key operation */
1925 return( mbedtls_rsa_public( ctx
, sig
, sig
) );
1928 /* Private key operation
1930 * In order to prevent Lenstra's attack, make the signature in a
1931 * temporary buffer and check it before returning it.
1934 sig_try
= mbedtls_calloc( 1, ctx
->len
);
1935 if( sig_try
== NULL
)
1936 return( MBEDTLS_ERR_MPI_ALLOC_FAILED
);
1938 verif
= mbedtls_calloc( 1, ctx
->len
);
1941 mbedtls_free( sig_try
);
1942 return( MBEDTLS_ERR_MPI_ALLOC_FAILED
);
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
) );
1948 if( mbedtls_safer_memcmp( verif
, sig
, ctx
->len
) != 0 )
1950 ret
= MBEDTLS_ERR_RSA_PRIVATE_FAILED
;
1954 memcpy( sig
, sig_try
, ctx
->len
);
1957 mbedtls_free( sig_try
);
1958 mbedtls_free( verif
);
1962 #endif /* MBEDTLS_PKCS1_V15 */
1965 * Do an RSA operation to sign the message digest
1967 int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context
*ctx
,
1968 int (*f_rng
)(void *, unsigned char *, size_t),
1971 mbedtls_md_type_t md_alg
,
1972 unsigned int hashlen
,
1973 const unsigned char *hash
,
1974 unsigned char *sig
)
1976 switch( ctx
->padding
)
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
);
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
);
1991 return( MBEDTLS_ERR_RSA_INVALID_PADDING
);
1995 #if defined(MBEDTLS_PKCS1_V21)
1997 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
1999 int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context
*ctx
,
2000 int (*f_rng
)(void *, unsigned char *, size_t),
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
)
2013 unsigned char *hash_start
;
2014 unsigned char result
[MBEDTLS_MD_MAX_SIZE
];
2015 unsigned char zeros
[8];
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
];
2022 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V21
)
2023 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2027 if( siglen
< 16 || siglen
> sizeof( buf
) )
2028 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2030 ret
= ( mode
== MBEDTLS_RSA_PUBLIC
)
2031 ? mbedtls_rsa_public( ctx
, sig
, buf
)
2032 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, sig
, buf
);
2039 if( buf
[siglen
- 1] != 0xBC )
2040 return( MBEDTLS_ERR_RSA_INVALID_PADDING
);
2042 if( md_alg
!= MBEDTLS_MD_NONE
)
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
);
2049 hashlen
= mbedtls_md_get_size( md_info
);
2052 md_info
= mbedtls_md_info_from_type( mgf1_hash_id
);
2053 if( md_info
== NULL
)
2054 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2056 hlen
= mbedtls_md_get_size( md_info
);
2058 memset( zeros
, 0, 8 );
2061 * Note: EMSA-PSS verification is over the length of N - 1 bits
2063 msb
= mbedtls_mpi_bitlen( &ctx
->N
) - 1;
2065 if( buf
[0] >> ( 8 - siglen
* 8 + msb
) )
2066 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2068 /* Compensate for boundary condition when applying mask */
2075 if( siglen
< hlen
+ 2 )
2076 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2077 hash_start
= p
+ siglen
- hlen
- 1;
2079 mbedtls_md_init( &md_ctx
);
2080 if( ( ret
= mbedtls_md_setup( &md_ctx
, md_info
, 0 ) ) != 0 )
2083 ret
= mgf_mask( p
, siglen
- hlen
- 1, hash_start
, hlen
, &md_ctx
);
2087 buf
[0] &= 0xFF >> ( siglen
* 8 - msb
);
2089 while( p
< hash_start
- 1 && *p
== 0 )
2094 ret
= MBEDTLS_ERR_RSA_INVALID_PADDING
;
2098 observed_salt_len
= hash_start
- p
;
2100 if( expected_salt_len
!= MBEDTLS_RSA_SALT_LEN_ANY
&&
2101 observed_salt_len
!= (size_t) expected_salt_len
)
2103 ret
= MBEDTLS_ERR_RSA_INVALID_PADDING
;
2108 * Generate H = Hash( M' )
2110 ret
= mbedtls_md_starts( &md_ctx
);
2113 ret
= mbedtls_md_update( &md_ctx
, zeros
, 8 );
2116 ret
= mbedtls_md_update( &md_ctx
, hash
, hashlen
);
2119 ret
= mbedtls_md_update( &md_ctx
, p
, observed_salt_len
);
2122 ret
= mbedtls_md_finish( &md_ctx
, result
);
2126 if( memcmp( hash_start
, result
, hlen
) != 0 )
2128 ret
= MBEDTLS_ERR_RSA_VERIFY_FAILED
;
2133 mbedtls_md_free( &md_ctx
);
2139 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2141 int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context
*ctx
,
2142 int (*f_rng
)(void *, unsigned char *, size_t),
2145 mbedtls_md_type_t md_alg
,
2146 unsigned int hashlen
,
2147 const unsigned char *hash
,
2148 const unsigned char *sig
)
2150 mbedtls_md_type_t mgf1_hash_id
= ( ctx
->hash_id
!= MBEDTLS_MD_NONE
)
2151 ? (mbedtls_md_type_t
) ctx
->hash_id
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
,
2160 #endif /* MBEDTLS_PKCS1_V21 */
2162 #if defined(MBEDTLS_PKCS1_V15)
2164 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2166 int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context
*ctx
,
2167 int (*f_rng
)(void *, unsigned char *, size_t),
2170 mbedtls_md_type_t md_alg
,
2171 unsigned int hashlen
,
2172 const unsigned char *hash
,
2173 const unsigned char *sig
)
2176 const size_t sig_len
= ctx
->len
;
2177 unsigned char *encoded
= NULL
, *encoded_expected
= NULL
;
2179 if( mode
== MBEDTLS_RSA_PRIVATE
&& ctx
->padding
!= MBEDTLS_RSA_PKCS_V15
)
2180 return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA
);
2183 * Prepare expected PKCS1 v1.5 encoding of hash.
2186 if( ( encoded
= mbedtls_calloc( 1, sig_len
) ) == NULL
||
2187 ( encoded_expected
= mbedtls_calloc( 1, sig_len
) ) == NULL
)
2189 ret
= MBEDTLS_ERR_MPI_ALLOC_FAILED
;
2193 if( ( ret
= rsa_rsassa_pkcs1_v15_encode( md_alg
, hashlen
, hash
, sig_len
,
2194 encoded_expected
) ) != 0 )
2198 * Apply RSA primitive to get what should be PKCS1 encoded hash.
2201 ret
= ( mode
== MBEDTLS_RSA_PUBLIC
)
2202 ? mbedtls_rsa_public( ctx
, sig
, encoded
)
2203 : mbedtls_rsa_private( ctx
, f_rng
, p_rng
, sig
, encoded
);
2211 if( ( ret
= mbedtls_safer_memcmp( encoded
, encoded_expected
,
2214 ret
= MBEDTLS_ERR_RSA_VERIFY_FAILED
;
2220 if( encoded
!= NULL
)
2222 mbedtls_zeroize( encoded
, sig_len
);
2223 mbedtls_free( encoded
);
2226 if( encoded_expected
!= NULL
)
2228 mbedtls_zeroize( encoded_expected
, sig_len
);
2229 mbedtls_free( encoded_expected
);
2234 #endif /* MBEDTLS_PKCS1_V15 */
2237 * Do an RSA operation and check the message digest
2239 int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context
*ctx
,
2240 int (*f_rng
)(void *, unsigned char *, size_t),
2243 mbedtls_md_type_t md_alg
,
2244 unsigned int hashlen
,
2245 const unsigned char *hash
,
2246 const unsigned char *sig
)
2248 switch( ctx
->padding
)
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
);
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
);
2263 return( MBEDTLS_ERR_RSA_INVALID_PADDING
);
2268 * Copy the components of an RSA key
2270 int mbedtls_rsa_copy( mbedtls_rsa_context
*dst
, const mbedtls_rsa_context
*src
)
2274 dst
->ver
= src
->ver
;
2275 dst
->len
= src
->len
;
2277 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst
->N
, &src
->N
) );
2278 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst
->E
, &src
->E
) );
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
) );
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
) );
2292 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst
->RN
, &src
->RN
) );
2294 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst
->Vi
, &src
->Vi
) );
2295 MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst
->Vf
, &src
->Vf
) );
2297 dst
->padding
= src
->padding
;
2298 dst
->hash_id
= src
->hash_id
;
2302 mbedtls_rsa_free( dst
);
2308 * Free the components of an RSA key
2310 void mbedtls_rsa_free( mbedtls_rsa_context
*ctx
)
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
);
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 */
2323 #if defined(MBEDTLS_THREADING_C)
2324 mbedtls_mutex_free( &ctx
->mutex
);
2328 #endif /* !MBEDTLS_RSA_ALT */
2330 #if defined(MBEDTLS_SELF_TEST)
2332 #include "mbedtls/sha1.h"
2335 * Example RSA-1024 keypair, for test purposes
2339 #define RSA_N "9292758453063D803DD603D5E777D788" \
2340 "8ED1D5BF35786190FA2F23EBC0848AEA" \
2341 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2342 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2343 "93A89813FBF3C4F8066D2D800F7C38A8" \
2344 "1AE31942917403FF4946B0A83D3D3E05" \
2345 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2346 "5E94BB77B07507233A0BC7BAC8F90F79"
2348 #define RSA_E "10001"
2350 #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
2351 "66CA472BC44D253102F8B4A9D3BFA750" \
2352 "91386C0077937FE33FA3252D28855837" \
2353 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2354 "DF79C5CE07EE72C7F123142198164234" \
2355 "CABB724CF78B8173B9F880FC86322407" \
2356 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2357 "071513A1E85B5DFA031F21ECAE91A34D"
2359 #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2360 "2C01CAD19EA484A87EA4377637E75500" \
2361 "FCB2005C5C7DD6EC4AC023CDA285D796" \
2362 "C3D9E75E1EFC42488BB4F1D13AC30A57"
2364 #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
2365 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2366 "910E4168387E3C30AA1E00C339A79508" \
2367 "8452DD96A9A5EA5D9DCA68DA636032AF"
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"
2373 #if defined(MBEDTLS_PKCS1_V15)
2374 static int myrand( void *rng_state
, unsigned char *output
, size_t len
)
2376 #if !defined(__OpenBSD__)
2379 if( rng_state
!= NULL
)
2382 for( i
= 0; i
< len
; ++i
)
2385 if( rng_state
!= NULL
)
2388 arc4random_buf( output
, len
);
2389 #endif /* !OpenBSD */
2393 #endif /* MBEDTLS_PKCS1_V15 */
2398 int mbedtls_rsa_self_test( int verbose
)
2401 #if defined(MBEDTLS_PKCS1_V15)
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];
2413 mbedtls_mpi_init( &K
);
2414 mbedtls_rsa_init( &rsa
, MBEDTLS_RSA_PKCS_V15
, 0 );
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
) );
2427 MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa
) );
2430 mbedtls_printf( " RSA key validation: " );
2432 if( mbedtls_rsa_check_pubkey( &rsa
) != 0 ||
2433 mbedtls_rsa_check_privkey( &rsa
) != 0 )
2436 mbedtls_printf( "failed\n" );
2443 mbedtls_printf( "passed\n PKCS#1 encryption : " );
2445 memcpy( rsa_plaintext
, RSA_PT
, PT_LEN
);
2447 if( mbedtls_rsa_pkcs1_encrypt( &rsa
, myrand
, NULL
, MBEDTLS_RSA_PUBLIC
,
2448 PT_LEN
, rsa_plaintext
,
2449 rsa_ciphertext
) != 0 )
2452 mbedtls_printf( "failed\n" );
2459 mbedtls_printf( "passed\n PKCS#1 decryption : " );
2461 if( mbedtls_rsa_pkcs1_decrypt( &rsa
, myrand
, NULL
, MBEDTLS_RSA_PRIVATE
,
2462 &len
, rsa_ciphertext
, rsa_decrypted
,
2463 sizeof(rsa_decrypted
) ) != 0 )
2466 mbedtls_printf( "failed\n" );
2472 if( memcmp( rsa_decrypted
, rsa_plaintext
, len
) != 0 )
2475 mbedtls_printf( "failed\n" );
2482 mbedtls_printf( "passed\n" );
2484 #if defined(MBEDTLS_SHA1_C)
2486 mbedtls_printf( " PKCS#1 data sign : " );
2488 if( mbedtls_sha1_ret( rsa_plaintext
, PT_LEN
, sha1sum
) != 0 )
2491 mbedtls_printf( "failed\n" );
2496 if( mbedtls_rsa_pkcs1_sign( &rsa
, myrand
, NULL
,
2497 MBEDTLS_RSA_PRIVATE
, MBEDTLS_MD_SHA1
, 0,
2498 sha1sum
, rsa_ciphertext
) != 0 )
2501 mbedtls_printf( "failed\n" );
2508 mbedtls_printf( "passed\n PKCS#1 sig. verify: " );
2510 if( mbedtls_rsa_pkcs1_verify( &rsa
, NULL
, NULL
,
2511 MBEDTLS_RSA_PUBLIC
, MBEDTLS_MD_SHA1
, 0,
2512 sha1sum
, rsa_ciphertext
) != 0 )
2515 mbedtls_printf( "failed\n" );
2522 mbedtls_printf( "passed\n" );
2523 #endif /* MBEDTLS_SHA1_C */
2526 mbedtls_printf( "\n" );
2529 mbedtls_mpi_free( &K
);
2530 mbedtls_rsa_free( &rsa
);
2531 #else /* MBEDTLS_PKCS1_V15 */
2533 #endif /* MBEDTLS_PKCS1_V15 */
2537 #endif /* MBEDTLS_SELF_TEST */
2539 #endif /* MBEDTLS_RSA_C */