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