xref: /reactos/dll/3rdparty/mbedtls/rsa.c (revision c2c66aff)
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  *  The following sources were referenced in the design of this implementation
25  *  of the RSA algorithm:
26  *
27  *  [1] A method for obtaining digital signatures and public-key cryptosystems
28  *      R Rivest, A Shamir, and L Adleman
29  *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
30  *
31  *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
32  *      Menezes, van Oorschot and Vanstone
33  *
34  *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
35  *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
36  *      Stefan Mangard
37  *      https://arxiv.org/abs/1702.08719v2
38  *
39  */
40 
41 #if !defined(MBEDTLS_CONFIG_FILE)
42 #include "mbedtls/config.h"
43 #else
44 #include MBEDTLS_CONFIG_FILE
45 #endif
46 
47 #if defined(MBEDTLS_RSA_C)
48 
49 #include "mbedtls/rsa.h"
50 #include "mbedtls/oid.h"
51 
52 #include <string.h>
53 
54 #if defined(MBEDTLS_PKCS1_V21)
55 #include "mbedtls/md.h"
56 #endif
57 
58 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)
59 #include <stdlib.h>
60 #endif
61 
62 #if defined(MBEDTLS_PLATFORM_C)
63 #include "mbedtls/platform.h"
64 #else
65 #include <stdio.h>
66 #define mbedtls_printf printf
67 #define mbedtls_calloc calloc
68 #define mbedtls_free   free
69 #endif
70 
71 /* Implementation that should never be optimized out by the compiler */
72 static void mbedtls_zeroize( void *v, size_t n ) {
73     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
74 }
75 
76 /*
77  * Initialize an RSA context
78  */
79 void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
80                int padding,
81                int hash_id )
82 {
83     memset( ctx, 0, sizeof( mbedtls_rsa_context ) );
84 
85     mbedtls_rsa_set_padding( ctx, padding, hash_id );
86 
87 #if defined(MBEDTLS_THREADING_C)
88     mbedtls_mutex_init( &ctx->mutex );
89 #endif
90 }
91 
92 /*
93  * Set padding for an existing RSA context
94  */
95 void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id )
96 {
97     ctx->padding = padding;
98     ctx->hash_id = hash_id;
99 }
100 
101 #if defined(MBEDTLS_GENPRIME)
102 
103 /*
104  * Generate an RSA keypair
105  */
106 int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
107                  int (*f_rng)(void *, unsigned char *, size_t),
108                  void *p_rng,
109                  unsigned int nbits, int exponent )
110 {
111     int ret;
112     mbedtls_mpi P1, Q1, H, G;
113 
114     if( f_rng == NULL || nbits < 128 || exponent < 3 )
115         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
116 
117     if( nbits % 2 )
118         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
119 
120     mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 );
121     mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G );
122 
123     /*
124      * find primes P and Q with Q < P so that:
125      * GCD( E, (P-1)*(Q-1) ) == 1
126      */
127     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) );
128 
129     do
130     {
131         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0,
132                                 f_rng, p_rng ) );
133 
134         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0,
135                                 f_rng, p_rng ) );
136 
137         if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) == 0 )
138             continue;
139 
140         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );
141         if( mbedtls_mpi_bitlen( &ctx->N ) != nbits )
142             continue;
143 
144         if( mbedtls_mpi_cmp_mpi( &ctx->P, &ctx->Q ) < 0 )
145                                 mbedtls_mpi_swap( &ctx->P, &ctx->Q );
146 
147         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
148         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
149         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &P1, &Q1 ) );
150         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H  ) );
151     }
152     while( mbedtls_mpi_cmp_int( &G, 1 ) != 0 );
153 
154     /*
155      * D  = E^-1 mod ((P-1)*(Q-1))
156      * DP = D mod (P - 1)
157      * DQ = D mod (Q - 1)
158      * QP = Q^-1 mod P
159      */
160     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D , &ctx->E, &H  ) );
161     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->DP, &ctx->D, &P1 ) );
162     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->DQ, &ctx->D, &Q1 ) );
163     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->QP, &ctx->Q, &ctx->P ) );
164 
165     ctx->len = ( mbedtls_mpi_bitlen( &ctx->N ) + 7 ) >> 3;
166 
167 cleanup:
168 
169     mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 ); mbedtls_mpi_free( &H ); mbedtls_mpi_free( &G );
170 
171     if( ret != 0 )
172     {
173         mbedtls_rsa_free( ctx );
174         return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret );
175     }
176 
177     return( 0 );
178 }
179 
180 #endif /* MBEDTLS_GENPRIME */
181 
182 /*
183  * Check a public RSA key
184  */
185 int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )
186 {
187     if( !ctx->N.p || !ctx->E.p )
188         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
189 
190     if( ( ctx->N.p[0] & 1 ) == 0 ||
191         ( ctx->E.p[0] & 1 ) == 0 )
192         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
193 
194     if( mbedtls_mpi_bitlen( &ctx->N ) < 128 ||
195         mbedtls_mpi_bitlen( &ctx->N ) > MBEDTLS_MPI_MAX_BITS )
196         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
197 
198     if( mbedtls_mpi_bitlen( &ctx->E ) < 2 ||
199         mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 )
200         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
201 
202     return( 0 );
203 }
204 
205 /*
206  * Check a private RSA key
207  */
208 int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )
209 {
210     int ret;
211     mbedtls_mpi PQ, DE, P1, Q1, H, I, G, G2, L1, L2, DP, DQ, QP;
212 
213     if( ( ret = mbedtls_rsa_check_pubkey( ctx ) ) != 0 )
214         return( ret );
215 
216     if( !ctx->P.p || !ctx->Q.p || !ctx->D.p )
217         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
218 
219     mbedtls_mpi_init( &PQ ); mbedtls_mpi_init( &DE ); mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 );
220     mbedtls_mpi_init( &H  ); mbedtls_mpi_init( &I  ); mbedtls_mpi_init( &G  ); mbedtls_mpi_init( &G2 );
221     mbedtls_mpi_init( &L1 ); mbedtls_mpi_init( &L2 ); mbedtls_mpi_init( &DP ); mbedtls_mpi_init( &DQ );
222     mbedtls_mpi_init( &QP );
223 
224     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &PQ, &ctx->P, &ctx->Q ) );
225     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DE, &ctx->D, &ctx->E ) );
226     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
227     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
228     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &P1, &Q1 ) );
229     MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H  ) );
230 
231     MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G2, &P1, &Q1 ) );
232     MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L1, &L2, &H, &G2 ) );
233     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &I, &DE, &L1  ) );
234 
235     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &DP, &ctx->D, &P1 ) );
236     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &DQ, &ctx->D, &Q1 ) );
237     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &QP, &ctx->Q, &ctx->P ) );
238     /*
239      * Check for a valid PKCS1v2 private key
240      */
241     if( mbedtls_mpi_cmp_mpi( &PQ, &ctx->N ) != 0 ||
242         mbedtls_mpi_cmp_mpi( &DP, &ctx->DP ) != 0 ||
243         mbedtls_mpi_cmp_mpi( &DQ, &ctx->DQ ) != 0 ||
244         mbedtls_mpi_cmp_mpi( &QP, &ctx->QP ) != 0 ||
245         mbedtls_mpi_cmp_int( &L2, 0 ) != 0 ||
246         mbedtls_mpi_cmp_int( &I, 1 ) != 0 ||
247         mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
248     {
249         ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
250     }
251 
252 cleanup:
253     mbedtls_mpi_free( &PQ ); mbedtls_mpi_free( &DE ); mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 );
254     mbedtls_mpi_free( &H  ); mbedtls_mpi_free( &I  ); mbedtls_mpi_free( &G  ); mbedtls_mpi_free( &G2 );
255     mbedtls_mpi_free( &L1 ); mbedtls_mpi_free( &L2 ); mbedtls_mpi_free( &DP ); mbedtls_mpi_free( &DQ );
256     mbedtls_mpi_free( &QP );
257 
258     if( ret == MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )
259         return( ret );
260 
261     if( ret != 0 )
262         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED + ret );
263 
264     return( 0 );
265 }
266 
267 /*
268  * Check if contexts holding a public and private key match
269  */
270 int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv )
271 {
272     if( mbedtls_rsa_check_pubkey( pub ) != 0 ||
273         mbedtls_rsa_check_privkey( prv ) != 0 )
274     {
275         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
276     }
277 
278     if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 ||
279         mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 )
280     {
281         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
282     }
283 
284     return( 0 );
285 }
286 
287 /*
288  * Do an RSA public key operation
289  */
290 int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
291                 const unsigned char *input,
292                 unsigned char *output )
293 {
294     int ret;
295     size_t olen;
296     mbedtls_mpi T;
297 
298     mbedtls_mpi_init( &T );
299 
300 #if defined(MBEDTLS_THREADING_C)
301     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
302         return( ret );
303 #endif
304 
305     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
306 
307     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
308     {
309         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
310         goto cleanup;
311     }
312 
313     olen = ctx->len;
314     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) );
315     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
316 
317 cleanup:
318 #if defined(MBEDTLS_THREADING_C)
319     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
320         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
321 #endif
322 
323     mbedtls_mpi_free( &T );
324 
325     if( ret != 0 )
326         return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret );
327 
328     return( 0 );
329 }
330 
331 /*
332  * Generate or update blinding values, see section 10 of:
333  *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
334  *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
335  *  Berlin Heidelberg, 1996. p. 104-113.
336  */
337 static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
338                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
339 {
340     int ret, count = 0;
341 
342     if( ctx->Vf.p != NULL )
343     {
344         /* We already have blinding values, just update them by squaring */
345         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );
346         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
347         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );
348         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) );
349 
350         goto cleanup;
351     }
352 
353     /* Unblinding value: Vf = random number, invertible mod N */
354     do {
355         if( count++ > 10 )
356             return( MBEDTLS_ERR_RSA_RNG_FAILED );
357 
358         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) );
359         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi, &ctx->Vf, &ctx->N ) );
360     } while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 );
361 
362     /* Blinding value: Vi =  Vf^(-e) mod N */
363     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) );
364     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );
365 
366 
367 cleanup:
368     return( ret );
369 }
370 
371 /*
372  * Exponent blinding supposed to prevent side-channel attacks using multiple
373  * traces of measurements to recover the RSA key. The more collisions are there,
374  * the more bits of the key can be recovered. See [3].
375  *
376  * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
377  * observations on avarage.
378  *
379  * For example with 28 byte blinding to achieve 2 collisions the adversary has
380  * to make 2^112 observations on avarage.
381  *
382  * (With the currently (as of 2017 April) known best algorithms breaking 2048
383  * bit RSA requires approximately as much time as trying out 2^112 random keys.
384  * Thus in this sense with 28 byte blinding the security is not reduced by
385  * side-channel attacks like the one in [3])
386  *
387  * This countermeasure does not help if the key recovery is possible with a
388  * single trace.
389  */
390 #define RSA_EXPONENT_BLINDING 28
391 
392 /*
393  * Do an RSA private key operation
394  */
395 int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
396                  int (*f_rng)(void *, unsigned char *, size_t),
397                  void *p_rng,
398                  const unsigned char *input,
399                  unsigned char *output )
400 {
401     int ret;
402     size_t olen;
403     mbedtls_mpi T, T1, T2;
404     mbedtls_mpi P1, Q1, R;
405 #if defined(MBEDTLS_RSA_NO_CRT)
406     mbedtls_mpi D_blind;
407     mbedtls_mpi *D = &ctx->D;
408 #else
409     mbedtls_mpi DP_blind, DQ_blind;
410     mbedtls_mpi *DP = &ctx->DP;
411     mbedtls_mpi *DQ = &ctx->DQ;
412 #endif
413 
414     /* Make sure we have private key info, prevent possible misuse */
415     if( ctx->P.p == NULL || ctx->Q.p == NULL || ctx->D.p == NULL )
416         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
417 
418     mbedtls_mpi_init( &T ); mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 );
419     mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &R );
420 
421 
422     if( f_rng != NULL )
423     {
424 #if defined(MBEDTLS_RSA_NO_CRT)
425         mbedtls_mpi_init( &D_blind );
426 #else
427         mbedtls_mpi_init( &DP_blind );
428         mbedtls_mpi_init( &DQ_blind );
429 #endif
430     }
431 
432 
433 #if defined(MBEDTLS_THREADING_C)
434     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
435         return( ret );
436 #endif
437 
438     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
439     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
440     {
441         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
442         goto cleanup;
443     }
444 
445     if( f_rng != NULL )
446     {
447         /*
448          * Blinding
449          * T = T * Vi mod N
450          */
451         MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) );
452         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) );
453         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
454 
455         /*
456          * Exponent blinding
457          */
458         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
459         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
460 
461 #if defined(MBEDTLS_RSA_NO_CRT)
462         /*
463          * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
464          */
465         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
466                          f_rng, p_rng ) );
467         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) );
468         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) );
469         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) );
470 
471         D = &D_blind;
472 #else
473         /*
474          * DP_blind = ( P - 1 ) * R + DP
475          */
476         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
477                          f_rng, p_rng ) );
478         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );
479         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,
480                     &ctx->DP ) );
481 
482         DP = &DP_blind;
483 
484         /*
485          * DQ_blind = ( Q - 1 ) * R + DQ
486          */
487         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
488                          f_rng, p_rng ) );
489         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) );
490         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind,
491                     &ctx->DQ ) );
492 
493         DQ = &DQ_blind;
494 #endif /* MBEDTLS_RSA_NO_CRT */
495     }
496 
497 #if defined(MBEDTLS_RSA_NO_CRT)
498     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) );
499 #else
500     /*
501      * Faster decryption using the CRT
502      *
503      * T1 = input ^ dP mod P
504      * T2 = input ^ dQ mod Q
505      */
506     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T1, &T, DP, &ctx->P, &ctx->RP ) );
507     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T2, &T, DQ, &ctx->Q, &ctx->RQ ) );
508 
509     /*
510      * T = (T1 - T2) * (Q^-1 mod P) mod P
511      */
512     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &T1, &T2 ) );
513     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1, &T, &ctx->QP ) );
514     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T1, &ctx->P ) );
515 
516     /*
517      * T = T2 + T * Q
518      */
519     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1, &T, &ctx->Q ) );
520     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &T2, &T1 ) );
521 #endif /* MBEDTLS_RSA_NO_CRT */
522 
523     if( f_rng != NULL )
524     {
525         /*
526          * Unblind
527          * T = T * Vf mod N
528          */
529         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) );
530         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
531     }
532 
533     olen = ctx->len;
534     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
535 
536 cleanup:
537 #if defined(MBEDTLS_THREADING_C)
538     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
539         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
540 #endif
541 
542     mbedtls_mpi_free( &T ); mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 );
543     mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 ); mbedtls_mpi_free( &R );
544 
545     if( f_rng != NULL )
546     {
547 #if defined(MBEDTLS_RSA_NO_CRT)
548         mbedtls_mpi_free( &D_blind );
549 #else
550         mbedtls_mpi_free( &DP_blind );
551         mbedtls_mpi_free( &DQ_blind );
552 #endif
553     }
554 
555     if( ret != 0 )
556         return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret );
557 
558     return( 0 );
559 }
560 
561 #if defined(MBEDTLS_PKCS1_V21)
562 /**
563  * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
564  *
565  * \param dst       buffer to mask
566  * \param dlen      length of destination buffer
567  * \param src       source of the mask generation
568  * \param slen      length of the source buffer
569  * \param md_ctx    message digest context to use
570  */
571 static void mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
572                       size_t slen, mbedtls_md_context_t *md_ctx )
573 {
574     unsigned char mask[MBEDTLS_MD_MAX_SIZE];
575     unsigned char counter[4];
576     unsigned char *p;
577     unsigned int hlen;
578     size_t i, use_len;
579 
580     memset( mask, 0, MBEDTLS_MD_MAX_SIZE );
581     memset( counter, 0, 4 );
582 
583     hlen = mbedtls_md_get_size( md_ctx->md_info );
584 
585     /* Generate and apply dbMask */
586     p = dst;
587 
588     while( dlen > 0 )
589     {
590         use_len = hlen;
591         if( dlen < hlen )
592             use_len = dlen;
593 
594         mbedtls_md_starts( md_ctx );
595         mbedtls_md_update( md_ctx, src, slen );
596         mbedtls_md_update( md_ctx, counter, 4 );
597         mbedtls_md_finish( md_ctx, mask );
598 
599         for( i = 0; i < use_len; ++i )
600             *p++ ^= mask[i];
601 
602         counter[3]++;
603 
604         dlen -= use_len;
605     }
606 
607     mbedtls_zeroize( mask, sizeof( mask ) );
608 }
609 #endif /* MBEDTLS_PKCS1_V21 */
610 
611 #if defined(MBEDTLS_PKCS1_V21)
612 /*
613  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
614  */
615 int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
616                             int (*f_rng)(void *, unsigned char *, size_t),
617                             void *p_rng,
618                             int mode,
619                             const unsigned char *label, size_t label_len,
620                             size_t ilen,
621                             const unsigned char *input,
622                             unsigned char *output )
623 {
624     size_t olen;
625     int ret;
626     unsigned char *p = output;
627     unsigned int hlen;
628     const mbedtls_md_info_t *md_info;
629     mbedtls_md_context_t md_ctx;
630 
631     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
632         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
633 
634     if( f_rng == NULL )
635         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
636 
637     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
638     if( md_info == NULL )
639         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
640 
641     olen = ctx->len;
642     hlen = mbedtls_md_get_size( md_info );
643 
644     /* first comparison checks for overflow */
645     if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
646         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
647 
648     memset( output, 0, olen );
649 
650     *p++ = 0;
651 
652     /* Generate a random octet string seed */
653     if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
654         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
655 
656     p += hlen;
657 
658     /* Construct DB */
659     mbedtls_md( md_info, label, label_len, p );
660     p += hlen;
661     p += olen - 2 * hlen - 2 - ilen;
662     *p++ = 1;
663     memcpy( p, input, ilen );
664 
665     mbedtls_md_init( &md_ctx );
666     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
667     {
668         mbedtls_md_free( &md_ctx );
669         return( ret );
670     }
671 
672     /* maskedDB: Apply dbMask to DB */
673     mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
674                &md_ctx );
675 
676     /* maskedSeed: Apply seedMask to seed */
677     mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
678                &md_ctx );
679 
680     mbedtls_md_free( &md_ctx );
681 
682     return( ( mode == MBEDTLS_RSA_PUBLIC )
683             ? mbedtls_rsa_public(  ctx, output, output )
684             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
685 }
686 #endif /* MBEDTLS_PKCS1_V21 */
687 
688 #if defined(MBEDTLS_PKCS1_V15)
689 /*
690  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
691  */
692 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
693                                  int (*f_rng)(void *, unsigned char *, size_t),
694                                  void *p_rng,
695                                  int mode, size_t ilen,
696                                  const unsigned char *input,
697                                  unsigned char *output )
698 {
699     size_t nb_pad, olen;
700     int ret;
701     unsigned char *p = output;
702 
703     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
704         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
705 
706     // We don't check p_rng because it won't be dereferenced here
707     if( f_rng == NULL || input == NULL || output == NULL )
708         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
709 
710     olen = ctx->len;
711 
712     /* first comparison checks for overflow */
713     if( ilen + 11 < ilen || olen < ilen + 11 )
714         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
715 
716     nb_pad = olen - 3 - ilen;
717 
718     *p++ = 0;
719     if( mode == MBEDTLS_RSA_PUBLIC )
720     {
721         *p++ = MBEDTLS_RSA_CRYPT;
722 
723         while( nb_pad-- > 0 )
724         {
725             int rng_dl = 100;
726 
727             do {
728                 ret = f_rng( p_rng, p, 1 );
729             } while( *p == 0 && --rng_dl && ret == 0 );
730 
731             /* Check if RNG failed to generate data */
732             if( rng_dl == 0 || ret != 0 )
733                 return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
734 
735             p++;
736         }
737     }
738     else
739     {
740         *p++ = MBEDTLS_RSA_SIGN;
741 
742         while( nb_pad-- > 0 )
743             *p++ = 0xFF;
744     }
745 
746     *p++ = 0;
747     memcpy( p, input, ilen );
748 
749     return( ( mode == MBEDTLS_RSA_PUBLIC )
750             ? mbedtls_rsa_public(  ctx, output, output )
751             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
752 }
753 #endif /* MBEDTLS_PKCS1_V15 */
754 
755 /*
756  * Add the message padding, then do an RSA operation
757  */
758 int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
759                        int (*f_rng)(void *, unsigned char *, size_t),
760                        void *p_rng,
761                        int mode, size_t ilen,
762                        const unsigned char *input,
763                        unsigned char *output )
764 {
765     switch( ctx->padding )
766     {
767 #if defined(MBEDTLS_PKCS1_V15)
768         case MBEDTLS_RSA_PKCS_V15:
769             return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,
770                                                 input, output );
771 #endif
772 
773 #if defined(MBEDTLS_PKCS1_V21)
774         case MBEDTLS_RSA_PKCS_V21:
775             return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,
776                                            ilen, input, output );
777 #endif
778 
779         default:
780             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
781     }
782 }
783 
784 #if defined(MBEDTLS_PKCS1_V21)
785 /*
786  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
787  */
788 int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
789                             int (*f_rng)(void *, unsigned char *, size_t),
790                             void *p_rng,
791                             int mode,
792                             const unsigned char *label, size_t label_len,
793                             size_t *olen,
794                             const unsigned char *input,
795                             unsigned char *output,
796                             size_t output_max_len )
797 {
798     int ret;
799     size_t ilen, i, pad_len;
800     unsigned char *p, bad, pad_done;
801     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
802     unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
803     unsigned int hlen;
804     const mbedtls_md_info_t *md_info;
805     mbedtls_md_context_t md_ctx;
806 
807     /*
808      * Parameters sanity checks
809      */
810     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
811         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
812 
813     ilen = ctx->len;
814 
815     if( ilen < 16 || ilen > sizeof( buf ) )
816         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
817 
818     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
819     if( md_info == NULL )
820         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
821 
822     hlen = mbedtls_md_get_size( md_info );
823 
824     // checking for integer underflow
825     if( 2 * hlen + 2 > ilen )
826         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
827 
828     /*
829      * RSA operation
830      */
831     ret = ( mode == MBEDTLS_RSA_PUBLIC )
832           ? mbedtls_rsa_public(  ctx, input, buf )
833           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
834 
835     if( ret != 0 )
836         goto cleanup;
837 
838     /*
839      * Unmask data and generate lHash
840      */
841     mbedtls_md_init( &md_ctx );
842     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
843     {
844         mbedtls_md_free( &md_ctx );
845         goto cleanup;
846     }
847 
848 
849     /* Generate lHash */
850     mbedtls_md( md_info, label, label_len, lhash );
851 
852     /* seed: Apply seedMask to maskedSeed */
853     mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
854                &md_ctx );
855 
856     /* DB: Apply dbMask to maskedDB */
857     mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
858                &md_ctx );
859 
860     mbedtls_md_free( &md_ctx );
861 
862     /*
863      * Check contents, in "constant-time"
864      */
865     p = buf;
866     bad = 0;
867 
868     bad |= *p++; /* First byte must be 0 */
869 
870     p += hlen; /* Skip seed */
871 
872     /* Check lHash */
873     for( i = 0; i < hlen; i++ )
874         bad |= lhash[i] ^ *p++;
875 
876     /* Get zero-padding len, but always read till end of buffer
877      * (minus one, for the 01 byte) */
878     pad_len = 0;
879     pad_done = 0;
880     for( i = 0; i < ilen - 2 * hlen - 2; i++ )
881     {
882         pad_done |= p[i];
883         pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
884     }
885 
886     p += pad_len;
887     bad |= *p++ ^ 0x01;
888 
889     /*
890      * The only information "leaked" is whether the padding was correct or not
891      * (eg, no data is copied if it was not correct). This meets the
892      * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
893      * the different error conditions.
894      */
895     if( bad != 0 )
896     {
897         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
898         goto cleanup;
899     }
900 
901     if( ilen - ( p - buf ) > output_max_len )
902     {
903         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
904         goto cleanup;
905     }
906 
907     *olen = ilen - (p - buf);
908     memcpy( output, p, *olen );
909     ret = 0;
910 
911 cleanup:
912     mbedtls_zeroize( buf, sizeof( buf ) );
913     mbedtls_zeroize( lhash, sizeof( lhash ) );
914 
915     return( ret );
916 }
917 #endif /* MBEDTLS_PKCS1_V21 */
918 
919 #if defined(MBEDTLS_PKCS1_V15)
920 /*
921  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
922  */
923 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
924                                  int (*f_rng)(void *, unsigned char *, size_t),
925                                  void *p_rng,
926                                  int mode, size_t *olen,
927                                  const unsigned char *input,
928                                  unsigned char *output,
929                                  size_t output_max_len)
930 {
931     int ret;
932     size_t ilen, pad_count = 0, i;
933     unsigned char *p, bad, pad_done = 0;
934     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
935 
936     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
937         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
938 
939     ilen = ctx->len;
940 
941     if( ilen < 16 || ilen > sizeof( buf ) )
942         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
943 
944     ret = ( mode == MBEDTLS_RSA_PUBLIC )
945           ? mbedtls_rsa_public(  ctx, input, buf )
946           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
947 
948     if( ret != 0 )
949         goto cleanup;
950 
951     p = buf;
952     bad = 0;
953 
954     /*
955      * Check and get padding len in "constant-time"
956      */
957     bad |= *p++; /* First byte must be 0 */
958 
959     /* This test does not depend on secret data */
960     if( mode == MBEDTLS_RSA_PRIVATE )
961     {
962         bad |= *p++ ^ MBEDTLS_RSA_CRYPT;
963 
964         /* Get padding len, but always read till end of buffer
965          * (minus one, for the 00 byte) */
966         for( i = 0; i < ilen - 3; i++ )
967         {
968             pad_done  |= ((p[i] | (unsigned char)-p[i]) >> 7) ^ 1;
969             pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
970         }
971 
972         p += pad_count;
973         bad |= *p++; /* Must be zero */
974     }
975     else
976     {
977         bad |= *p++ ^ MBEDTLS_RSA_SIGN;
978 
979         /* Get padding len, but always read till end of buffer
980          * (minus one, for the 00 byte) */
981         for( i = 0; i < ilen - 3; i++ )
982         {
983             pad_done |= ( p[i] != 0xFF );
984             pad_count += ( pad_done == 0 );
985         }
986 
987         p += pad_count;
988         bad |= *p++; /* Must be zero */
989     }
990 
991     bad |= ( pad_count < 8 );
992 
993     if( bad )
994     {
995         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
996         goto cleanup;
997     }
998 
999     if( ilen - ( p - buf ) > output_max_len )
1000     {
1001         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1002         goto cleanup;
1003     }
1004 
1005     *olen = ilen - (p - buf);
1006     memcpy( output, p, *olen );
1007     ret = 0;
1008 
1009 cleanup:
1010     mbedtls_zeroize( buf, sizeof( buf ) );
1011 
1012     return( ret );
1013 }
1014 #endif /* MBEDTLS_PKCS1_V15 */
1015 
1016 /*
1017  * Do an RSA operation, then remove the message padding
1018  */
1019 int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
1020                        int (*f_rng)(void *, unsigned char *, size_t),
1021                        void *p_rng,
1022                        int mode, size_t *olen,
1023                        const unsigned char *input,
1024                        unsigned char *output,
1025                        size_t output_max_len)
1026 {
1027     switch( ctx->padding )
1028     {
1029 #if defined(MBEDTLS_PKCS1_V15)
1030         case MBEDTLS_RSA_PKCS_V15:
1031             return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,
1032                                                 input, output, output_max_len );
1033 #endif
1034 
1035 #if defined(MBEDTLS_PKCS1_V21)
1036         case MBEDTLS_RSA_PKCS_V21:
1037             return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,
1038                                            olen, input, output,
1039                                            output_max_len );
1040 #endif
1041 
1042         default:
1043             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1044     }
1045 }
1046 
1047 #if defined(MBEDTLS_PKCS1_V21)
1048 /*
1049  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
1050  */
1051 int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
1052                          int (*f_rng)(void *, unsigned char *, size_t),
1053                          void *p_rng,
1054                          int mode,
1055                          mbedtls_md_type_t md_alg,
1056                          unsigned int hashlen,
1057                          const unsigned char *hash,
1058                          unsigned char *sig )
1059 {
1060     size_t olen;
1061     unsigned char *p = sig;
1062     unsigned char salt[MBEDTLS_MD_MAX_SIZE];
1063     unsigned int slen, hlen, offset = 0;
1064     int ret;
1065     size_t msb;
1066     const mbedtls_md_info_t *md_info;
1067     mbedtls_md_context_t md_ctx;
1068 
1069     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
1070         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1071 
1072     if( f_rng == NULL )
1073         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1074 
1075     olen = ctx->len;
1076 
1077     if( md_alg != MBEDTLS_MD_NONE )
1078     {
1079         /* Gather length of hash to sign */
1080         md_info = mbedtls_md_info_from_type( md_alg );
1081         if( md_info == NULL )
1082             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1083 
1084         hashlen = mbedtls_md_get_size( md_info );
1085     }
1086 
1087     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
1088     if( md_info == NULL )
1089         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1090 
1091     hlen = mbedtls_md_get_size( md_info );
1092     slen = hlen;
1093 
1094     if( olen < hlen + slen + 2 )
1095         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1096 
1097     memset( sig, 0, olen );
1098 
1099     /* Generate salt of length slen */
1100     if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
1101         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
1102 
1103     /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
1104     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
1105     p += olen - hlen * 2 - 2;
1106     *p++ = 0x01;
1107     memcpy( p, salt, slen );
1108     p += slen;
1109 
1110     mbedtls_md_init( &md_ctx );
1111     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
1112     {
1113         mbedtls_md_free( &md_ctx );
1114         /* No need to zeroize salt: we didn't use it. */
1115         return( ret );
1116     }
1117 
1118     /* Generate H = Hash( M' ) */
1119     mbedtls_md_starts( &md_ctx );
1120     mbedtls_md_update( &md_ctx, p, 8 );
1121     mbedtls_md_update( &md_ctx, hash, hashlen );
1122     mbedtls_md_update( &md_ctx, salt, slen );
1123     mbedtls_md_finish( &md_ctx, p );
1124     mbedtls_zeroize( salt, sizeof( salt ) );
1125 
1126     /* Compensate for boundary condition when applying mask */
1127     if( msb % 8 == 0 )
1128         offset = 1;
1129 
1130     /* maskedDB: Apply dbMask to DB */
1131     mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx );
1132 
1133     mbedtls_md_free( &md_ctx );
1134 
1135     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
1136     sig[0] &= 0xFF >> ( olen * 8 - msb );
1137 
1138     p += hlen;
1139     *p++ = 0xBC;
1140 
1141     return( ( mode == MBEDTLS_RSA_PUBLIC )
1142             ? mbedtls_rsa_public(  ctx, sig, sig )
1143             : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) );
1144 }
1145 #endif /* MBEDTLS_PKCS1_V21 */
1146 
1147 #if defined(MBEDTLS_PKCS1_V15)
1148 /*
1149  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
1150  */
1151 /*
1152  * Do an RSA operation to sign the message digest
1153  */
1154 int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
1155                                int (*f_rng)(void *, unsigned char *, size_t),
1156                                void *p_rng,
1157                                int mode,
1158                                mbedtls_md_type_t md_alg,
1159                                unsigned int hashlen,
1160                                const unsigned char *hash,
1161                                unsigned char *sig )
1162 {
1163     size_t nb_pad, olen, oid_size = 0;
1164     unsigned char *p = sig;
1165     const char *oid = NULL;
1166     unsigned char *sig_try = NULL, *verif = NULL;
1167     size_t i;
1168     unsigned char diff;
1169     volatile unsigned char diff_no_optimize;
1170     int ret;
1171 
1172     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
1173         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1174 
1175     olen = ctx->len;
1176     nb_pad = olen - 3;
1177 
1178     if( md_alg != MBEDTLS_MD_NONE )
1179     {
1180         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
1181         if( md_info == NULL )
1182             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1183 
1184         if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
1185             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1186 
1187         nb_pad -= 10 + oid_size;
1188 
1189         hashlen = mbedtls_md_get_size( md_info );
1190     }
1191 
1192     nb_pad -= hashlen;
1193 
1194     if( ( nb_pad < 8 ) || ( nb_pad > olen ) )
1195         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1196 
1197     *p++ = 0;
1198     *p++ = MBEDTLS_RSA_SIGN;
1199     memset( p, 0xFF, nb_pad );
1200     p += nb_pad;
1201     *p++ = 0;
1202 
1203     if( md_alg == MBEDTLS_MD_NONE )
1204     {
1205         memcpy( p, hash, hashlen );
1206     }
1207     else
1208     {
1209         /*
1210          * DigestInfo ::= SEQUENCE {
1211          *   digestAlgorithm DigestAlgorithmIdentifier,
1212          *   digest Digest }
1213          *
1214          * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1215          *
1216          * Digest ::= OCTET STRING
1217          */
1218         *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1219         *p++ = (unsigned char) ( 0x08 + oid_size + hashlen );
1220         *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1221         *p++ = (unsigned char) ( 0x04 + oid_size );
1222         *p++ = MBEDTLS_ASN1_OID;
1223         *p++ = oid_size & 0xFF;
1224         memcpy( p, oid, oid_size );
1225         p += oid_size;
1226         *p++ = MBEDTLS_ASN1_NULL;
1227         *p++ = 0x00;
1228         *p++ = MBEDTLS_ASN1_OCTET_STRING;
1229         *p++ = hashlen;
1230         memcpy( p, hash, hashlen );
1231     }
1232 
1233     if( mode == MBEDTLS_RSA_PUBLIC )
1234         return( mbedtls_rsa_public(  ctx, sig, sig ) );
1235 
1236     /*
1237      * In order to prevent Lenstra's attack, make the signature in a
1238      * temporary buffer and check it before returning it.
1239      */
1240     sig_try = mbedtls_calloc( 1, ctx->len );
1241     if( sig_try == NULL )
1242         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
1243 
1244     verif   = mbedtls_calloc( 1, ctx->len );
1245     if( verif == NULL )
1246     {
1247         mbedtls_free( sig_try );
1248         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
1249     }
1250 
1251     MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) );
1252     MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) );
1253 
1254     /* Compare in constant time just in case */
1255     for( diff = 0, i = 0; i < ctx->len; i++ )
1256         diff |= verif[i] ^ sig[i];
1257     diff_no_optimize = diff;
1258 
1259     if( diff_no_optimize != 0 )
1260     {
1261         ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
1262         goto cleanup;
1263     }
1264 
1265     memcpy( sig, sig_try, ctx->len );
1266 
1267 cleanup:
1268     mbedtls_free( sig_try );
1269     mbedtls_free( verif );
1270 
1271     return( ret );
1272 }
1273 #endif /* MBEDTLS_PKCS1_V15 */
1274 
1275 /*
1276  * Do an RSA operation to sign the message digest
1277  */
1278 int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
1279                     int (*f_rng)(void *, unsigned char *, size_t),
1280                     void *p_rng,
1281                     int mode,
1282                     mbedtls_md_type_t md_alg,
1283                     unsigned int hashlen,
1284                     const unsigned char *hash,
1285                     unsigned char *sig )
1286 {
1287     switch( ctx->padding )
1288     {
1289 #if defined(MBEDTLS_PKCS1_V15)
1290         case MBEDTLS_RSA_PKCS_V15:
1291             return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,
1292                                               hashlen, hash, sig );
1293 #endif
1294 
1295 #if defined(MBEDTLS_PKCS1_V21)
1296         case MBEDTLS_RSA_PKCS_V21:
1297             return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
1298                                         hashlen, hash, sig );
1299 #endif
1300 
1301         default:
1302             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1303     }
1304 }
1305 
1306 #if defined(MBEDTLS_PKCS1_V21)
1307 /*
1308  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
1309  */
1310 int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
1311                                int (*f_rng)(void *, unsigned char *, size_t),
1312                                void *p_rng,
1313                                int mode,
1314                                mbedtls_md_type_t md_alg,
1315                                unsigned int hashlen,
1316                                const unsigned char *hash,
1317                                mbedtls_md_type_t mgf1_hash_id,
1318                                int expected_salt_len,
1319                                const unsigned char *sig )
1320 {
1321     int ret;
1322     size_t siglen;
1323     unsigned char *p;
1324     unsigned char result[MBEDTLS_MD_MAX_SIZE];
1325     unsigned char zeros[8];
1326     unsigned int hlen;
1327     size_t slen, msb;
1328     const mbedtls_md_info_t *md_info;
1329     mbedtls_md_context_t md_ctx;
1330     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1331 
1332     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
1333         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1334 
1335     siglen = ctx->len;
1336 
1337     if( siglen < 16 || siglen > sizeof( buf ) )
1338         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1339 
1340     ret = ( mode == MBEDTLS_RSA_PUBLIC )
1341           ? mbedtls_rsa_public(  ctx, sig, buf )
1342           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );
1343 
1344     if( ret != 0 )
1345         return( ret );
1346 
1347     p = buf;
1348 
1349     if( buf[siglen - 1] != 0xBC )
1350         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1351 
1352     if( md_alg != MBEDTLS_MD_NONE )
1353     {
1354         /* Gather length of hash to sign */
1355         md_info = mbedtls_md_info_from_type( md_alg );
1356         if( md_info == NULL )
1357             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1358 
1359         hashlen = mbedtls_md_get_size( md_info );
1360     }
1361 
1362     md_info = mbedtls_md_info_from_type( mgf1_hash_id );
1363     if( md_info == NULL )
1364         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1365 
1366     hlen = mbedtls_md_get_size( md_info );
1367     slen = siglen - hlen - 1; /* Currently length of salt + padding */
1368 
1369     memset( zeros, 0, 8 );
1370 
1371     /*
1372      * Note: EMSA-PSS verification is over the length of N - 1 bits
1373      */
1374     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
1375 
1376     /* Compensate for boundary condition when applying mask */
1377     if( msb % 8 == 0 )
1378     {
1379         p++;
1380         siglen -= 1;
1381     }
1382     if( buf[0] >> ( 8 - siglen * 8 + msb ) )
1383         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1384 
1385     mbedtls_md_init( &md_ctx );
1386     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
1387     {
1388         mbedtls_md_free( &md_ctx );
1389         return( ret );
1390     }
1391 
1392     mgf_mask( p, siglen - hlen - 1, p + siglen - hlen - 1, hlen, &md_ctx );
1393 
1394     buf[0] &= 0xFF >> ( siglen * 8 - msb );
1395 
1396     while( p < buf + siglen && *p == 0 )
1397         p++;
1398 
1399     if( p == buf + siglen ||
1400         *p++ != 0x01 )
1401     {
1402         mbedtls_md_free( &md_ctx );
1403         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1404     }
1405 
1406     /* Actual salt len */
1407     slen -= p - buf;
1408 
1409     if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
1410         slen != (size_t) expected_salt_len )
1411     {
1412         mbedtls_md_free( &md_ctx );
1413         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1414     }
1415 
1416     /*
1417      * Generate H = Hash( M' )
1418      */
1419     mbedtls_md_starts( &md_ctx );
1420     mbedtls_md_update( &md_ctx, zeros, 8 );
1421     mbedtls_md_update( &md_ctx, hash, hashlen );
1422     mbedtls_md_update( &md_ctx, p, slen );
1423     mbedtls_md_finish( &md_ctx, result );
1424 
1425     mbedtls_md_free( &md_ctx );
1426 
1427     if( memcmp( p + slen, result, hlen ) == 0 )
1428         return( 0 );
1429     else
1430         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1431 }
1432 
1433 /*
1434  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
1435  */
1436 int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
1437                            int (*f_rng)(void *, unsigned char *, size_t),
1438                            void *p_rng,
1439                            int mode,
1440                            mbedtls_md_type_t md_alg,
1441                            unsigned int hashlen,
1442                            const unsigned char *hash,
1443                            const unsigned char *sig )
1444 {
1445     mbedtls_md_type_t mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE )
1446                              ? (mbedtls_md_type_t) ctx->hash_id
1447                              : md_alg;
1448 
1449     return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,
1450                                        md_alg, hashlen, hash,
1451                                        mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,
1452                                        sig ) );
1453 
1454 }
1455 #endif /* MBEDTLS_PKCS1_V21 */
1456 
1457 #if defined(MBEDTLS_PKCS1_V15)
1458 /*
1459  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
1460  */
1461 int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
1462                                  int (*f_rng)(void *, unsigned char *, size_t),
1463                                  void *p_rng,
1464                                  int mode,
1465                                  mbedtls_md_type_t md_alg,
1466                                  unsigned int hashlen,
1467                                  const unsigned char *hash,
1468                                  const unsigned char *sig )
1469 {
1470     int ret;
1471     size_t len, siglen, asn1_len;
1472     unsigned char *p, *p0, *end;
1473     mbedtls_md_type_t msg_md_alg;
1474     const mbedtls_md_info_t *md_info;
1475     mbedtls_asn1_buf oid;
1476     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1477 
1478     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
1479         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1480 
1481     siglen = ctx->len;
1482 
1483     if( siglen < 16 || siglen > sizeof( buf ) )
1484         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1485 
1486     ret = ( mode == MBEDTLS_RSA_PUBLIC )
1487           ? mbedtls_rsa_public(  ctx, sig, buf )
1488           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );
1489 
1490     if( ret != 0 )
1491         return( ret );
1492 
1493     p = buf;
1494 
1495     if( *p++ != 0 || *p++ != MBEDTLS_RSA_SIGN )
1496         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1497 
1498     while( *p != 0 )
1499     {
1500         if( p >= buf + siglen - 1 || *p != 0xFF )
1501             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1502         p++;
1503     }
1504     p++; /* skip 00 byte */
1505 
1506     /* We've read: 00 01 PS 00 where PS must be at least 8 bytes */
1507     if( p - buf < 11 )
1508         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1509 
1510     len = siglen - ( p - buf );
1511 
1512     if( len == hashlen && md_alg == MBEDTLS_MD_NONE )
1513     {
1514         if( memcmp( p, hash, hashlen ) == 0 )
1515             return( 0 );
1516         else
1517             return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1518     }
1519 
1520     md_info = mbedtls_md_info_from_type( md_alg );
1521     if( md_info == NULL )
1522         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1523     hashlen = mbedtls_md_get_size( md_info );
1524 
1525     end = p + len;
1526 
1527     /*
1528      * Parse the ASN.1 structure inside the PKCS#1 v1.5 structure.
1529      * Insist on 2-byte length tags, to protect against variants of
1530      * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification.
1531      */
1532     p0 = p;
1533     if( ( ret = mbedtls_asn1_get_tag( &p, end, &asn1_len,
1534             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1535         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1536     if( p != p0 + 2 || asn1_len + 2 != len )
1537         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1538 
1539     p0 = p;
1540     if( ( ret = mbedtls_asn1_get_tag( &p, end, &asn1_len,
1541             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
1542         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1543     if( p != p0 + 2 || asn1_len + 6 + hashlen != len )
1544         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1545 
1546     p0 = p;
1547     if( ( ret = mbedtls_asn1_get_tag( &p, end, &oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
1548         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1549     if( p != p0 + 2 )
1550         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1551 
1552     oid.p = p;
1553     p += oid.len;
1554 
1555     if( mbedtls_oid_get_md_alg( &oid, &msg_md_alg ) != 0 )
1556         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1557 
1558     if( md_alg != msg_md_alg )
1559         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1560 
1561     /*
1562      * assume the algorithm parameters must be NULL
1563      */
1564     p0 = p;
1565     if( ( ret = mbedtls_asn1_get_tag( &p, end, &asn1_len, MBEDTLS_ASN1_NULL ) ) != 0 )
1566         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1567     if( p != p0 + 2 )
1568         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1569 
1570     p0 = p;
1571     if( ( ret = mbedtls_asn1_get_tag( &p, end, &asn1_len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
1572         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1573     if( p != p0 + 2 || asn1_len != hashlen )
1574         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1575 
1576     if( memcmp( p, hash, hashlen ) != 0 )
1577         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1578 
1579     p += hashlen;
1580 
1581     if( p != end )
1582         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
1583 
1584     return( 0 );
1585 }
1586 #endif /* MBEDTLS_PKCS1_V15 */
1587 
1588 /*
1589  * Do an RSA operation and check the message digest
1590  */
1591 int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
1592                       int (*f_rng)(void *, unsigned char *, size_t),
1593                       void *p_rng,
1594                       int mode,
1595                       mbedtls_md_type_t md_alg,
1596                       unsigned int hashlen,
1597                       const unsigned char *hash,
1598                       const unsigned char *sig )
1599 {
1600     switch( ctx->padding )
1601     {
1602 #if defined(MBEDTLS_PKCS1_V15)
1603         case MBEDTLS_RSA_PKCS_V15:
1604             return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,
1605                                                 hashlen, hash, sig );
1606 #endif
1607 
1608 #if defined(MBEDTLS_PKCS1_V21)
1609         case MBEDTLS_RSA_PKCS_V21:
1610             return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,
1611                                           hashlen, hash, sig );
1612 #endif
1613 
1614         default:
1615             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
1616     }
1617 }
1618 
1619 /*
1620  * Copy the components of an RSA key
1621  */
1622 int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
1623 {
1624     int ret;
1625 
1626     dst->ver = src->ver;
1627     dst->len = src->len;
1628 
1629     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) );
1630     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) );
1631 
1632     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) );
1633     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) );
1634     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) );
1635     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) );
1636     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) );
1637     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) );
1638 
1639     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) );
1640     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) );
1641     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) );
1642 
1643     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) );
1644     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) );
1645 
1646     dst->padding = src->padding;
1647     dst->hash_id = src->hash_id;
1648 
1649 cleanup:
1650     if( ret != 0 )
1651         mbedtls_rsa_free( dst );
1652 
1653     return( ret );
1654 }
1655 
1656 /*
1657  * Free the components of an RSA key
1658  */
1659 void mbedtls_rsa_free( mbedtls_rsa_context *ctx )
1660 {
1661     mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->Vf );
1662     mbedtls_mpi_free( &ctx->RQ ); mbedtls_mpi_free( &ctx->RP ); mbedtls_mpi_free( &ctx->RN );
1663     mbedtls_mpi_free( &ctx->QP ); mbedtls_mpi_free( &ctx->DQ ); mbedtls_mpi_free( &ctx->DP );
1664     mbedtls_mpi_free( &ctx->Q  ); mbedtls_mpi_free( &ctx->P  ); mbedtls_mpi_free( &ctx->D );
1665     mbedtls_mpi_free( &ctx->E  ); mbedtls_mpi_free( &ctx->N  );
1666 
1667 #if defined(MBEDTLS_THREADING_C)
1668     mbedtls_mutex_free( &ctx->mutex );
1669 #endif
1670 }
1671 
1672 #if defined(MBEDTLS_SELF_TEST)
1673 
1674 #include "mbedtls/sha1.h"
1675 
1676 /*
1677  * Example RSA-1024 keypair, for test purposes
1678  */
1679 #define KEY_LEN 128
1680 
1681 #define RSA_N   "9292758453063D803DD603D5E777D788" \
1682                 "8ED1D5BF35786190FA2F23EBC0848AEA" \
1683                 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
1684                 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
1685                 "93A89813FBF3C4F8066D2D800F7C38A8" \
1686                 "1AE31942917403FF4946B0A83D3D3E05" \
1687                 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
1688                 "5E94BB77B07507233A0BC7BAC8F90F79"
1689 
1690 #define RSA_E   "10001"
1691 
1692 #define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
1693                 "66CA472BC44D253102F8B4A9D3BFA750" \
1694                 "91386C0077937FE33FA3252D28855837" \
1695                 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
1696                 "DF79C5CE07EE72C7F123142198164234" \
1697                 "CABB724CF78B8173B9F880FC86322407" \
1698                 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
1699                 "071513A1E85B5DFA031F21ECAE91A34D"
1700 
1701 #define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
1702                 "2C01CAD19EA484A87EA4377637E75500" \
1703                 "FCB2005C5C7DD6EC4AC023CDA285D796" \
1704                 "C3D9E75E1EFC42488BB4F1D13AC30A57"
1705 
1706 #define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
1707                 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
1708                 "910E4168387E3C30AA1E00C339A79508" \
1709                 "8452DD96A9A5EA5D9DCA68DA636032AF"
1710 
1711 #define RSA_DP  "C1ACF567564274FB07A0BBAD5D26E298" \
1712                 "3C94D22288ACD763FD8E5600ED4A702D" \
1713                 "F84198A5F06C2E72236AE490C93F07F8" \
1714                 "3CC559CD27BC2D1CA488811730BB5725"
1715 
1716 #define RSA_DQ  "4959CBF6F8FEF750AEE6977C155579C7" \
1717                 "D8AAEA56749EA28623272E4F7D0592AF" \
1718                 "7C1F1313CAC9471B5C523BFE592F517B" \
1719                 "407A1BD76C164B93DA2D32A383E58357"
1720 
1721 #define RSA_QP  "9AE7FBC99546432DF71896FC239EADAE" \
1722                 "F38D18D2B2F0E2DD275AA977E2BF4411" \
1723                 "F5A3B2A5D33605AEBBCCBA7FEB9F2D2F" \
1724                 "A74206CEC169D74BF5A8C50D6F48EA08"
1725 
1726 #define PT_LEN  24
1727 #define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
1728                 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
1729 
1730 #if defined(MBEDTLS_PKCS1_V15)
1731 static int myrand( void *rng_state, unsigned char *output, size_t len )
1732 {
1733 #if !defined(__OpenBSD__)
1734     size_t i;
1735 
1736     if( rng_state != NULL )
1737         rng_state  = NULL;
1738 
1739     for( i = 0; i < len; ++i )
1740         output[i] = rand();
1741 #else
1742     if( rng_state != NULL )
1743         rng_state = NULL;
1744 
1745     arc4random_buf( output, len );
1746 #endif /* !OpenBSD */
1747 
1748     return( 0 );
1749 }
1750 #endif /* MBEDTLS_PKCS1_V15 */
1751 
1752 /*
1753  * Checkup routine
1754  */
1755 int mbedtls_rsa_self_test( int verbose )
1756 {
1757     int ret = 0;
1758 #if defined(MBEDTLS_PKCS1_V15)
1759     size_t len;
1760     mbedtls_rsa_context rsa;
1761     unsigned char rsa_plaintext[PT_LEN];
1762     unsigned char rsa_decrypted[PT_LEN];
1763     unsigned char rsa_ciphertext[KEY_LEN];
1764 #if defined(MBEDTLS_SHA1_C)
1765     unsigned char sha1sum[20];
1766 #endif
1767 
1768     mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
1769 
1770     rsa.len = KEY_LEN;
1771     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.N , 16, RSA_N  ) );
1772     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.E , 16, RSA_E  ) );
1773     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.D , 16, RSA_D  ) );
1774     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.P , 16, RSA_P  ) );
1775     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.Q , 16, RSA_Q  ) );
1776     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.DP, 16, RSA_DP ) );
1777     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.DQ, 16, RSA_DQ ) );
1778     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &rsa.QP, 16, RSA_QP ) );
1779 
1780     if( verbose != 0 )
1781         mbedtls_printf( "  RSA key validation: " );
1782 
1783     if( mbedtls_rsa_check_pubkey(  &rsa ) != 0 ||
1784         mbedtls_rsa_check_privkey( &rsa ) != 0 )
1785     {
1786         if( verbose != 0 )
1787             mbedtls_printf( "failed\n" );
1788 
1789         return( 1 );
1790     }
1791 
1792     if( verbose != 0 )
1793         mbedtls_printf( "passed\n  PKCS#1 encryption : " );
1794 
1795     memcpy( rsa_plaintext, RSA_PT, PT_LEN );
1796 
1797     if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC, PT_LEN,
1798                            rsa_plaintext, rsa_ciphertext ) != 0 )
1799     {
1800         if( verbose != 0 )
1801             mbedtls_printf( "failed\n" );
1802 
1803         return( 1 );
1804     }
1805 
1806     if( verbose != 0 )
1807         mbedtls_printf( "passed\n  PKCS#1 decryption : " );
1808 
1809     if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, &len,
1810                            rsa_ciphertext, rsa_decrypted,
1811                            sizeof(rsa_decrypted) ) != 0 )
1812     {
1813         if( verbose != 0 )
1814             mbedtls_printf( "failed\n" );
1815 
1816         return( 1 );
1817     }
1818 
1819     if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
1820     {
1821         if( verbose != 0 )
1822             mbedtls_printf( "failed\n" );
1823 
1824         return( 1 );
1825     }
1826 
1827     if( verbose != 0 )
1828         mbedtls_printf( "passed\n" );
1829 
1830 #if defined(MBEDTLS_SHA1_C)
1831     if( verbose != 0 )
1832         mbedtls_printf( "  PKCS#1 data sign  : " );
1833 
1834     mbedtls_sha1( rsa_plaintext, PT_LEN, sha1sum );
1835 
1836     if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
1837                         sha1sum, rsa_ciphertext ) != 0 )
1838     {
1839         if( verbose != 0 )
1840             mbedtls_printf( "failed\n" );
1841 
1842         return( 1 );
1843     }
1844 
1845     if( verbose != 0 )
1846         mbedtls_printf( "passed\n  PKCS#1 sig. verify: " );
1847 
1848     if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
1849                           sha1sum, rsa_ciphertext ) != 0 )
1850     {
1851         if( verbose != 0 )
1852             mbedtls_printf( "failed\n" );
1853 
1854         return( 1 );
1855     }
1856 
1857     if( verbose != 0 )
1858         mbedtls_printf( "passed\n" );
1859 #endif /* MBEDTLS_SHA1_C */
1860 
1861     if( verbose != 0 )
1862         mbedtls_printf( "\n" );
1863 
1864 cleanup:
1865     mbedtls_rsa_free( &rsa );
1866 #else /* MBEDTLS_PKCS1_V15 */
1867     ((void) verbose);
1868 #endif /* MBEDTLS_PKCS1_V15 */
1869     return( ret );
1870 }
1871 
1872 #endif /* MBEDTLS_SELF_TEST */
1873 
1874 #endif /* MBEDTLS_RSA_C */
1875