Kenji Arai / TYBLE16_mbedlized_os5_several_examples_1st

Dependencies:   nRF51_Vdd TextLCD BME280

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers rsa.c Source File

rsa.c

00001 /*
00002  *  The RSA public-key cryptosystem
00003  *
00004  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
00005  *  SPDX-License-Identifier: Apache-2.0
00006  *
00007  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
00008  *  not use this file except in compliance with the License.
00009  *  You may obtain a copy of the License at
00010  *
00011  *  http://www.apache.org/licenses/LICENSE-2.0
00012  *
00013  *  Unless required by applicable law or agreed to in writing, software
00014  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00015  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00016  *  See the License for the specific language governing permissions and
00017  *  limitations under the License.
00018  *
00019  *  This file is part of mbed TLS (https://tls.mbed.org)
00020  */
00021 
00022 /*
00023  *  The following sources were referenced in the design of this implementation
00024  *  of the RSA algorithm:
00025  *
00026  *  [1] A method for obtaining digital signatures and public-key cryptosystems
00027  *      R Rivest, A Shamir, and L Adleman
00028  *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
00029  *
00030  *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
00031  *      Menezes, van Oorschot and Vanstone
00032  *
00033  *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
00034  *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
00035  *      Stefan Mangard
00036  *      https://arxiv.org/abs/1702.08719v2
00037  *
00038  */
00039 
00040 #if !defined(MBEDTLS_CONFIG_FILE)
00041 #include "mbedtls/config.h"
00042 #else
00043 #include MBEDTLS_CONFIG_FILE
00044 #endif
00045 
00046 #if defined(MBEDTLS_RSA_C)
00047 
00048 #include "mbedtls/rsa.h"
00049 #include "mbedtls/rsa_internal.h"
00050 #include "mbedtls/oid.h"
00051 #include "mbedtls/platform_util.h"
00052 
00053 #include <string.h>
00054 
00055 #if defined(MBEDTLS_PKCS1_V21)
00056 #include "mbedtls/md.h"
00057 #endif
00058 
00059 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)
00060 #include <stdlib.h>
00061 #endif
00062 
00063 #if defined(MBEDTLS_PLATFORM_C)
00064 #include "mbedtls/platform.h"
00065 #else
00066 #include <stdio.h>
00067 #define mbedtls_printf printf
00068 #define mbedtls_calloc calloc
00069 #define mbedtls_free   free
00070 #endif
00071 
00072 #if !defined(MBEDTLS_RSA_ALT)
00073 
00074 #if defined(MBEDTLS_PKCS1_V15)
00075 /* constant-time buffer comparison */
00076 static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
00077 {
00078     size_t i;
00079     const unsigned char *A = (const unsigned char *) a;
00080     const unsigned char *B = (const unsigned char *) b;
00081     unsigned char diff = 0;
00082 
00083     for( i = 0; i < n; i++ )
00084         diff |= A[i] ^ B[i];
00085 
00086     return( diff );
00087 }
00088 #endif /* MBEDTLS_PKCS1_V15 */
00089 
00090 int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
00091                         const mbedtls_mpi *N,
00092                         const mbedtls_mpi *P, const mbedtls_mpi *Q,
00093                         const mbedtls_mpi *D, const mbedtls_mpi *E )
00094 {
00095     int ret;
00096 
00097     if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N , N ) ) != 0 ) ||
00098         ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->P , P ) ) != 0 ) ||
00099         ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->Q , Q ) ) != 0 ) ||
00100         ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->D , D ) ) != 0 ) ||
00101         ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->E , E ) ) != 0 ) )
00102     {
00103         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00104     }
00105 
00106     if( N != NULL )
00107         ctx->len  = mbedtls_mpi_size( &ctx->N  );
00108 
00109     return( 0 );
00110 }
00111 
00112 int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,
00113                             unsigned char const *N, size_t N_len,
00114                             unsigned char const *P, size_t P_len,
00115                             unsigned char const *Q, size_t Q_len,
00116                             unsigned char const *D, size_t D_len,
00117                             unsigned char const *E, size_t E_len )
00118 {
00119     int ret = 0;
00120 
00121     if( N != NULL )
00122     {
00123         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N , N, N_len ) );
00124         ctx->len  = mbedtls_mpi_size( &ctx->N  );
00125     }
00126 
00127     if( P != NULL )
00128         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P , P, P_len ) );
00129 
00130     if( Q != NULL )
00131         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q , Q, Q_len ) );
00132 
00133     if( D != NULL )
00134         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D , D, D_len ) );
00135 
00136     if( E != NULL )
00137         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E , E, E_len ) );
00138 
00139 cleanup:
00140 
00141     if( ret != 0 )
00142         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00143 
00144     return( 0 );
00145 }
00146 
00147 /*
00148  * Checks whether the context fields are set in such a way
00149  * that the RSA primitives will be able to execute without error.
00150  * It does *not* make guarantees for consistency of the parameters.
00151  */
00152 static int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv,
00153                               int blinding_needed )
00154 {
00155 #if !defined(MBEDTLS_RSA_NO_CRT)
00156     /* blinding_needed is only used for NO_CRT to decide whether
00157      * P,Q need to be present or not. */
00158     ((void) blinding_needed);
00159 #endif
00160 
00161     if( ctx->len  != mbedtls_mpi_size( &ctx->N  ) ||
00162         ctx->len  > MBEDTLS_MPI_MAX_SIZE )
00163     {
00164         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00165     }
00166 
00167     /*
00168      * 1. Modular exponentiation needs positive, odd moduli.
00169      */
00170 
00171     /* Modular exponentiation wrt. N is always used for
00172      * RSA public key operations. */
00173     if( mbedtls_mpi_cmp_int( &ctx->N , 0 ) <= 0 ||
00174         mbedtls_mpi_get_bit( &ctx->N , 0 ) == 0  )
00175     {
00176         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00177     }
00178 
00179 #if !defined(MBEDTLS_RSA_NO_CRT)
00180     /* Modular exponentiation for P and Q is only
00181      * used for private key operations and if CRT
00182      * is used. */
00183     if( is_priv &&
00184         ( mbedtls_mpi_cmp_int( &ctx->P , 0 ) <= 0 ||
00185           mbedtls_mpi_get_bit( &ctx->P , 0 ) == 0 ||
00186           mbedtls_mpi_cmp_int( &ctx->Q , 0 ) <= 0 ||
00187           mbedtls_mpi_get_bit( &ctx->Q , 0 ) == 0  ) )
00188     {
00189         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00190     }
00191 #endif /* !MBEDTLS_RSA_NO_CRT */
00192 
00193     /*
00194      * 2. Exponents must be positive
00195      */
00196 
00197     /* Always need E for public key operations */
00198     if( mbedtls_mpi_cmp_int( &ctx->E , 0 ) <= 0 )
00199         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00200 
00201 #if defined(MBEDTLS_RSA_NO_CRT)
00202     /* For private key operations, use D or DP & DQ
00203      * as (unblinded) exponents. */
00204     if( is_priv && mbedtls_mpi_cmp_int( &ctx->D , 0 ) <= 0 )
00205         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00206 #else
00207     if( is_priv &&
00208         ( mbedtls_mpi_cmp_int( &ctx->DP , 0 ) <= 0 ||
00209           mbedtls_mpi_cmp_int( &ctx->DQ , 0 ) <= 0  ) )
00210     {
00211         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00212     }
00213 #endif /* MBEDTLS_RSA_NO_CRT */
00214 
00215     /* Blinding shouldn't make exponents negative either,
00216      * so check that P, Q >= 1 if that hasn't yet been
00217      * done as part of 1. */
00218 #if defined(MBEDTLS_RSA_NO_CRT)
00219     if( is_priv && blinding_needed &&
00220         ( mbedtls_mpi_cmp_int( &ctx->P , 0 ) <= 0 ||
00221           mbedtls_mpi_cmp_int( &ctx->Q , 0 ) <= 0 ) )
00222     {
00223         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00224     }
00225 #endif
00226 
00227     /* It wouldn't lead to an error if it wasn't satisfied,
00228      * but check for QP >= 1 nonetheless. */
00229 #if !defined(MBEDTLS_RSA_NO_CRT)
00230     if( is_priv &&
00231         mbedtls_mpi_cmp_int( &ctx->QP , 0 ) <= 0 )
00232     {
00233         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00234     }
00235 #endif
00236 
00237     return( 0 );
00238 }
00239 
00240 int mbedtls_rsa_complete( mbedtls_rsa_context *ctx )
00241 {
00242     int ret = 0;
00243 
00244     const int have_N = ( mbedtls_mpi_cmp_int( &ctx->N , 0 ) != 0 );
00245     const int have_P = ( mbedtls_mpi_cmp_int( &ctx->P , 0 ) != 0 );
00246     const int have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q , 0 ) != 0 );
00247     const int have_D = ( mbedtls_mpi_cmp_int( &ctx->D , 0 ) != 0 );
00248     const int have_E = ( mbedtls_mpi_cmp_int( &ctx->E , 0 ) != 0 );
00249 
00250     /*
00251      * Check whether provided parameters are enough
00252      * to deduce all others. The following incomplete
00253      * parameter sets for private keys are supported:
00254      *
00255      * (1) P, Q missing.
00256      * (2) D and potentially N missing.
00257      *
00258      */
00259 
00260     const int n_missing  =              have_P &&  have_Q &&  have_D && have_E;
00261     const int pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
00262     const int d_missing  =              have_P &&  have_Q && !have_D && have_E;
00263     const int is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
00264 
00265     /* These three alternatives are mutually exclusive */
00266     const int is_priv = n_missing || pq_missing || d_missing;
00267 
00268     if( !is_priv && !is_pub )
00269         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00270 
00271     /*
00272      * Step 1: Deduce N if P, Q are provided.
00273      */
00274 
00275     if( !have_N && have_P && have_Q )
00276     {
00277         if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N , &ctx->P ,
00278                                          &ctx->Q  ) ) != 0 )
00279         {
00280             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00281         }
00282 
00283         ctx->len  = mbedtls_mpi_size( &ctx->N  );
00284     }
00285 
00286     /*
00287      * Step 2: Deduce and verify all remaining core parameters.
00288      */
00289 
00290     if( pq_missing )
00291     {
00292         ret = mbedtls_rsa_deduce_primes( &ctx->N , &ctx->E , &ctx->D ,
00293                                          &ctx->P , &ctx->Q  );
00294         if( ret != 0 )
00295             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00296 
00297     }
00298     else if( d_missing )
00299     {
00300         if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P ,
00301                                                          &ctx->Q ,
00302                                                          &ctx->E ,
00303                                                          &ctx->D  ) ) != 0 )
00304         {
00305             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00306         }
00307     }
00308 
00309     /*
00310      * Step 3: Deduce all additional parameters specific
00311      *         to our current RSA implementation.
00312      */
00313 
00314 #if !defined(MBEDTLS_RSA_NO_CRT)
00315     if( is_priv )
00316     {
00317         ret = mbedtls_rsa_deduce_crt( &ctx->P ,  &ctx->Q ,  &ctx->D ,
00318                                       &ctx->DP , &ctx->DQ , &ctx->QP  );
00319         if( ret != 0 )
00320             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00321     }
00322 #endif /* MBEDTLS_RSA_NO_CRT */
00323 
00324     /*
00325      * Step 3: Basic sanity checks
00326      */
00327 
00328     return( rsa_check_context( ctx, is_priv, 1 ) );
00329 }
00330 
00331 int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,
00332                             unsigned char *N, size_t N_len,
00333                             unsigned char *P, size_t P_len,
00334                             unsigned char *Q, size_t Q_len,
00335                             unsigned char *D, size_t D_len,
00336                             unsigned char *E, size_t E_len )
00337 {
00338     int ret = 0;
00339 
00340     /* Check if key is private or public */
00341     const int is_priv =
00342         mbedtls_mpi_cmp_int( &ctx->N , 0 ) != 0 &&
00343         mbedtls_mpi_cmp_int( &ctx->P , 0 ) != 0 &&
00344         mbedtls_mpi_cmp_int( &ctx->Q , 0 ) != 0 &&
00345         mbedtls_mpi_cmp_int( &ctx->D , 0 ) != 0 &&
00346         mbedtls_mpi_cmp_int( &ctx->E , 0 ) != 0;
00347 
00348     if( !is_priv )
00349     {
00350         /* If we're trying to export private parameters for a public key,
00351          * something must be wrong. */
00352         if( P != NULL || Q != NULL || D != NULL )
00353             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00354 
00355     }
00356 
00357     if( N != NULL )
00358         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N , N, N_len ) );
00359 
00360     if( P != NULL )
00361         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P , P, P_len ) );
00362 
00363     if( Q != NULL )
00364         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q , Q, Q_len ) );
00365 
00366     if( D != NULL )
00367         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D , D, D_len ) );
00368 
00369     if( E != NULL )
00370         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E , E, E_len ) );
00371 
00372 cleanup:
00373 
00374     return( ret );
00375 }
00376 
00377 int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
00378                         mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
00379                         mbedtls_mpi *D, mbedtls_mpi *E )
00380 {
00381     int ret;
00382 
00383     /* Check if key is private or public */
00384     int is_priv =
00385         mbedtls_mpi_cmp_int( &ctx->N , 0 ) != 0 &&
00386         mbedtls_mpi_cmp_int( &ctx->P , 0 ) != 0 &&
00387         mbedtls_mpi_cmp_int( &ctx->Q , 0 ) != 0 &&
00388         mbedtls_mpi_cmp_int( &ctx->D , 0 ) != 0 &&
00389         mbedtls_mpi_cmp_int( &ctx->E , 0 ) != 0;
00390 
00391     if( !is_priv )
00392     {
00393         /* If we're trying to export private parameters for a public key,
00394          * something must be wrong. */
00395         if( P != NULL || Q != NULL || D != NULL )
00396             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00397 
00398     }
00399 
00400     /* Export all requested core parameters. */
00401 
00402     if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N  ) ) != 0 ) ||
00403         ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P  ) ) != 0 ) ||
00404         ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q  ) ) != 0 ) ||
00405         ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D  ) ) != 0 ) ||
00406         ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E  ) ) != 0 ) )
00407     {
00408         return( ret );
00409     }
00410 
00411     return( 0 );
00412 }
00413 
00414 /*
00415  * Export CRT parameters
00416  * This must also be implemented if CRT is not used, for being able to
00417  * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
00418  * can be used in this case.
00419  */
00420 int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
00421                             mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )
00422 {
00423     int ret;
00424 
00425     /* Check if key is private or public */
00426     int is_priv =
00427         mbedtls_mpi_cmp_int( &ctx->N , 0 ) != 0 &&
00428         mbedtls_mpi_cmp_int( &ctx->P , 0 ) != 0 &&
00429         mbedtls_mpi_cmp_int( &ctx->Q , 0 ) != 0 &&
00430         mbedtls_mpi_cmp_int( &ctx->D , 0 ) != 0 &&
00431         mbedtls_mpi_cmp_int( &ctx->E , 0 ) != 0;
00432 
00433     if( !is_priv )
00434         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00435 
00436 #if !defined(MBEDTLS_RSA_NO_CRT)
00437     /* Export all requested blinding parameters. */
00438     if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP  ) ) != 0 ) ||
00439         ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ  ) ) != 0 ) ||
00440         ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP  ) ) != 0 ) )
00441     {
00442         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00443     }
00444 #else
00445     if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P , &ctx->Q , &ctx->D ,
00446                                         DP, DQ, QP ) ) != 0 )
00447     {
00448         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
00449     }
00450 #endif
00451 
00452     return( 0 );
00453 }
00454 
00455 /*
00456  * Initialize an RSA context
00457  */
00458 void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
00459                int padding,
00460                int hash_id )
00461 {
00462     memset( ctx, 0, sizeof( mbedtls_rsa_context ) );
00463 
00464     mbedtls_rsa_set_padding( ctx, padding, hash_id );
00465 
00466 #if defined(MBEDTLS_THREADING_C)
00467     mbedtls_mutex_init( &ctx->mutex  );
00468 #endif
00469 }
00470 
00471 /*
00472  * Set padding for an existing RSA context
00473  */
00474 void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id )
00475 {
00476     ctx->padding  = padding;
00477     ctx->hash_id  = hash_id;
00478 }
00479 
00480 /*
00481  * Get length in bytes of RSA modulus
00482  */
00483 
00484 size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )
00485 {
00486     return( ctx->len  );
00487 }
00488 
00489 
00490 #if defined(MBEDTLS_GENPRIME)
00491 
00492 /*
00493  * Generate an RSA keypair
00494  *
00495  * This generation method follows the RSA key pair generation procedure of
00496  * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
00497  */
00498 int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
00499                  int (*f_rng)(void *, unsigned char *, size_t),
00500                  void *p_rng,
00501                  unsigned int nbits, int exponent )
00502 {
00503     int ret;
00504     mbedtls_mpi H, G, L;
00505 
00506     if( f_rng == NULL || nbits < 128 || exponent < 3 )
00507         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00508 
00509     if( nbits % 2 )
00510         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00511 
00512     mbedtls_mpi_init( &H );
00513     mbedtls_mpi_init( &G );
00514     mbedtls_mpi_init( &L );
00515 
00516     /*
00517      * find primes P and Q with Q < P so that:
00518      * 1.  |P-Q| > 2^( nbits / 2 - 100 )
00519      * 2.  GCD( E, (P-1)*(Q-1) ) == 1
00520      * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
00521      */
00522     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E , exponent ) );
00523 
00524     do
00525     {
00526         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P , nbits >> 1, 0,
00527                                                 f_rng, p_rng ) );
00528 
00529         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q , nbits >> 1, 0,
00530                                                 f_rng, p_rng ) );
00531 
00532         /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
00533         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P , &ctx->Q  ) );
00534         if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) )
00535             continue;
00536 
00537         /* not required by any standards, but some users rely on the fact that P > Q */
00538         if( H.s  < 0 )
00539             mbedtls_mpi_swap( &ctx->P , &ctx->Q  );
00540 
00541         /* Temporarily replace P,Q by P-1, Q-1 */
00542         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P , &ctx->P , 1 ) );
00543         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q , &ctx->Q , 1 ) );
00544         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P , &ctx->Q  ) );
00545 
00546         /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
00547         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E , &H  ) );
00548         if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
00549             continue;
00550 
00551         /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
00552         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P , &ctx->Q  ) );
00553         MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) );
00554         MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D , &ctx->E , &L ) );
00555 
00556         if( mbedtls_mpi_bitlen( &ctx->D  ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a))
00557             continue;
00558 
00559         break;
00560     }
00561     while( 1 );
00562 
00563     /* Restore P,Q */
00564     MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P ,  &ctx->P , 1 ) );
00565     MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q ,  &ctx->Q , 1 ) );
00566 
00567     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N , &ctx->P , &ctx->Q  ) );
00568 
00569     ctx->len  = mbedtls_mpi_size( &ctx->N  );
00570 
00571 #if !defined(MBEDTLS_RSA_NO_CRT)
00572     /*
00573      * DP = D mod (P - 1)
00574      * DQ = D mod (Q - 1)
00575      * QP = Q^-1 mod P
00576      */
00577     MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P , &ctx->Q , &ctx->D ,
00578                                              &ctx->DP , &ctx->DQ , &ctx->QP  ) );
00579 #endif /* MBEDTLS_RSA_NO_CRT */
00580 
00581     /* Double-check */
00582     MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) );
00583 
00584 cleanup:
00585 
00586     mbedtls_mpi_free( &H );
00587     mbedtls_mpi_free( &G );
00588     mbedtls_mpi_free( &L );
00589 
00590     if( ret != 0 )
00591     {
00592         mbedtls_rsa_free( ctx );
00593         return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret );
00594     }
00595 
00596     return( 0 );
00597 }
00598 
00599 #endif /* MBEDTLS_GENPRIME */
00600 
00601 /*
00602  * Check a public RSA key
00603  */
00604 int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )
00605 {
00606     if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 )
00607         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00608 
00609     if( mbedtls_mpi_bitlen( &ctx->N  ) < 128 )
00610     {
00611         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00612     }
00613 
00614     if( mbedtls_mpi_get_bit( &ctx->E , 0 ) == 0 ||
00615         mbedtls_mpi_bitlen( &ctx->E  )     < 2  ||
00616         mbedtls_mpi_cmp_mpi( &ctx->E , &ctx->N  ) >= 0 )
00617     {
00618         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00619     }
00620 
00621     return( 0 );
00622 }
00623 
00624 /*
00625  * Check for the consistency of all fields in an RSA private key context
00626  */
00627 int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )
00628 {
00629     if( mbedtls_rsa_check_pubkey( ctx ) != 0 ||
00630         rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 )
00631     {
00632         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00633     }
00634 
00635     if( mbedtls_rsa_validate_params( &ctx->N , &ctx->P , &ctx->Q ,
00636                                      &ctx->D , &ctx->E , NULL, NULL ) != 0 )
00637     {
00638         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00639     }
00640 
00641 #if !defined(MBEDTLS_RSA_NO_CRT)
00642     else if( mbedtls_rsa_validate_crt( &ctx->P , &ctx->Q , &ctx->D ,
00643                                        &ctx->DP , &ctx->DQ , &ctx->QP  ) != 0 )
00644     {
00645         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00646     }
00647 #endif
00648 
00649     return( 0 );
00650 }
00651 
00652 /*
00653  * Check if contexts holding a public and private key match
00654  */
00655 int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,
00656                                 const mbedtls_rsa_context *prv )
00657 {
00658     if( mbedtls_rsa_check_pubkey( pub )  != 0 ||
00659         mbedtls_rsa_check_privkey( prv ) != 0 )
00660     {
00661         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00662     }
00663 
00664     if( mbedtls_mpi_cmp_mpi( &pub->N , &prv->N  ) != 0 ||
00665         mbedtls_mpi_cmp_mpi( &pub->E , &prv->E  ) != 0 )
00666     {
00667         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
00668     }
00669 
00670     return( 0 );
00671 }
00672 
00673 /*
00674  * Do an RSA public key operation
00675  */
00676 int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
00677                 const unsigned char *input,
00678                 unsigned char *output )
00679 {
00680     int ret;
00681     size_t olen;
00682     mbedtls_mpi T;
00683 
00684     if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) )
00685         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00686 
00687     mbedtls_mpi_init( &T );
00688 
00689 #if defined(MBEDTLS_THREADING_C)
00690     if( ( ret = mbedtls_mutex_lock( &ctx->mutex  ) ) != 0 )
00691         return( ret );
00692 #endif
00693 
00694     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len  ) );
00695 
00696     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N  ) >= 0 )
00697     {
00698         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
00699         goto cleanup;
00700     }
00701 
00702     olen = ctx->len ;
00703     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E , &ctx->N , &ctx->RN  ) );
00704     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
00705 
00706 cleanup:
00707 #if defined(MBEDTLS_THREADING_C)
00708     if( mbedtls_mutex_unlock( &ctx->mutex  ) != 0 )
00709         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
00710 #endif
00711 
00712     mbedtls_mpi_free( &T );
00713 
00714     if( ret != 0 )
00715         return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret );
00716 
00717     return( 0 );
00718 }
00719 
00720 /*
00721  * Generate or update blinding values, see section 10 of:
00722  *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
00723  *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
00724  *  Berlin Heidelberg, 1996. p. 104-113.
00725  */
00726 static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
00727                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
00728 {
00729     int ret, count = 0;
00730 
00731     if( ctx->Vf .p  != NULL )
00732     {
00733         /* We already have blinding values, just update them by squaring */
00734         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi , &ctx->Vi , &ctx->Vi  ) );
00735         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi , &ctx->Vi , &ctx->N  ) );
00736         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf , &ctx->Vf , &ctx->Vf  ) );
00737         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf , &ctx->Vf , &ctx->N  ) );
00738 
00739         goto cleanup;
00740     }
00741 
00742     /* Unblinding value: Vf = random number, invertible mod N */
00743     do {
00744         if( count++ > 10 )
00745             return( MBEDTLS_ERR_RSA_RNG_FAILED );
00746 
00747         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf , ctx->len  - 1, f_rng, p_rng ) );
00748         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi , &ctx->Vf , &ctx->N  ) );
00749     } while( mbedtls_mpi_cmp_int( &ctx->Vi , 1 ) != 0 );
00750 
00751     /* Blinding value: Vi =  Vf^(-e) mod N */
00752     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi , &ctx->Vf , &ctx->N  ) );
00753     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi , &ctx->Vi , &ctx->E , &ctx->N , &ctx->RN  ) );
00754 
00755 
00756 cleanup:
00757     return( ret );
00758 }
00759 
00760 /*
00761  * Exponent blinding supposed to prevent side-channel attacks using multiple
00762  * traces of measurements to recover the RSA key. The more collisions are there,
00763  * the more bits of the key can be recovered. See [3].
00764  *
00765  * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
00766  * observations on avarage.
00767  *
00768  * For example with 28 byte blinding to achieve 2 collisions the adversary has
00769  * to make 2^112 observations on avarage.
00770  *
00771  * (With the currently (as of 2017 April) known best algorithms breaking 2048
00772  * bit RSA requires approximately as much time as trying out 2^112 random keys.
00773  * Thus in this sense with 28 byte blinding the security is not reduced by
00774  * side-channel attacks like the one in [3])
00775  *
00776  * This countermeasure does not help if the key recovery is possible with a
00777  * single trace.
00778  */
00779 #define RSA_EXPONENT_BLINDING 28
00780 
00781 /*
00782  * Do an RSA private key operation
00783  */
00784 int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
00785                  int (*f_rng)(void *, unsigned char *, size_t),
00786                  void *p_rng,
00787                  const unsigned char *input,
00788                  unsigned char *output )
00789 {
00790     int ret;
00791     size_t olen;
00792 
00793     /* Temporary holding the result */
00794     mbedtls_mpi T;
00795 
00796     /* Temporaries holding P-1, Q-1 and the
00797      * exponent blinding factor, respectively. */
00798     mbedtls_mpi P1, Q1, R;
00799 
00800 #if !defined(MBEDTLS_RSA_NO_CRT)
00801     /* Temporaries holding the results mod p resp. mod q. */
00802     mbedtls_mpi TP, TQ;
00803 
00804     /* Temporaries holding the blinded exponents for
00805      * the mod p resp. mod q computation (if used). */
00806     mbedtls_mpi DP_blind, DQ_blind;
00807 
00808     /* Pointers to actual exponents to be used - either the unblinded
00809      * or the blinded ones, depending on the presence of a PRNG. */
00810     mbedtls_mpi *DP = &ctx->DP ;
00811     mbedtls_mpi *DQ = &ctx->DQ ;
00812 #else
00813     /* Temporary holding the blinded exponent (if used). */
00814     mbedtls_mpi D_blind;
00815 
00816     /* Pointer to actual exponent to be used - either the unblinded
00817      * or the blinded one, depending on the presence of a PRNG. */
00818     mbedtls_mpi *D = &ctx->D ;
00819 #endif /* MBEDTLS_RSA_NO_CRT */
00820 
00821     /* Temporaries holding the initial input and the double
00822      * checked result; should be the same in the end. */
00823     mbedtls_mpi I, C;
00824 
00825     if( rsa_check_context( ctx, 1             /* private key checks */,
00826                                 f_rng != NULL /* blinding y/n       */ ) != 0 )
00827     {
00828         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
00829     }
00830 
00831 #if defined(MBEDTLS_THREADING_C)
00832     if( ( ret = mbedtls_mutex_lock( &ctx->mutex  ) ) != 0 )
00833         return( ret );
00834 #endif
00835 
00836     /* MPI Initialization */
00837     mbedtls_mpi_init( &T );
00838 
00839     mbedtls_mpi_init( &P1 );
00840     mbedtls_mpi_init( &Q1 );
00841     mbedtls_mpi_init( &R );
00842 
00843     if( f_rng != NULL )
00844     {
00845 #if defined(MBEDTLS_RSA_NO_CRT)
00846         mbedtls_mpi_init( &D_blind );
00847 #else
00848         mbedtls_mpi_init( &DP_blind );
00849         mbedtls_mpi_init( &DQ_blind );
00850 #endif
00851     }
00852 
00853 #if !defined(MBEDTLS_RSA_NO_CRT)
00854     mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ );
00855 #endif
00856 
00857     mbedtls_mpi_init( &I );
00858     mbedtls_mpi_init( &C );
00859 
00860     /* End of MPI initialization */
00861 
00862     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len  ) );
00863     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N  ) >= 0 )
00864     {
00865         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
00866         goto cleanup;
00867     }
00868 
00869     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) );
00870 
00871     if( f_rng != NULL )
00872     {
00873         /*
00874          * Blinding
00875          * T = T * Vi mod N
00876          */
00877         MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) );
00878         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi  ) );
00879         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N  ) );
00880 
00881         /*
00882          * Exponent blinding
00883          */
00884         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P , 1 ) );
00885         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q , 1 ) );
00886 
00887 #if defined(MBEDTLS_RSA_NO_CRT)
00888         /*
00889          * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
00890          */
00891         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
00892                          f_rng, p_rng ) );
00893         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) );
00894         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) );
00895         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D  ) );
00896 
00897         D = &D_blind;
00898 #else
00899         /*
00900          * DP_blind = ( P - 1 ) * R + DP
00901          */
00902         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
00903                          f_rng, p_rng ) );
00904         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );
00905         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,
00906                     &ctx->DP  ) );
00907 
00908         DP = &DP_blind;
00909 
00910         /*
00911          * DQ_blind = ( Q - 1 ) * R + DQ
00912          */
00913         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
00914                          f_rng, p_rng ) );
00915         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) );
00916         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind,
00917                     &ctx->DQ  ) );
00918 
00919         DQ = &DQ_blind;
00920 #endif /* MBEDTLS_RSA_NO_CRT */
00921     }
00922 
00923 #if defined(MBEDTLS_RSA_NO_CRT)
00924     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N , &ctx->RN  ) );
00925 #else
00926     /*
00927      * Faster decryption using the CRT
00928      *
00929      * TP = input ^ dP mod P
00930      * TQ = input ^ dQ mod Q
00931      */
00932 
00933     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P , &ctx->RP  ) );
00934     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q , &ctx->RQ  ) );
00935 
00936     /*
00937      * T = (TP - TQ) * (Q^-1 mod P) mod P
00938      */
00939     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) );
00940     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP  ) );
00941     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P  ) );
00942 
00943     /*
00944      * T = TQ + T * Q
00945      */
00946     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q  ) );
00947     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) );
00948 #endif /* MBEDTLS_RSA_NO_CRT */
00949 
00950     if( f_rng != NULL )
00951     {
00952         /*
00953          * Unblind
00954          * T = T * Vf mod N
00955          */
00956         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf  ) );
00957         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N  ) );
00958     }
00959 
00960     /* Verify the result to prevent glitching attacks. */
00961     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E ,
00962                                           &ctx->N , &ctx->RN  ) );
00963     if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 )
00964     {
00965         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
00966         goto cleanup;
00967     }
00968 
00969     olen = ctx->len ;
00970     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
00971 
00972 cleanup:
00973 #if defined(MBEDTLS_THREADING_C)
00974     if( mbedtls_mutex_unlock( &ctx->mutex  ) != 0 )
00975         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
00976 #endif
00977 
00978     mbedtls_mpi_free( &P1 );
00979     mbedtls_mpi_free( &Q1 );
00980     mbedtls_mpi_free( &R );
00981 
00982     if( f_rng != NULL )
00983     {
00984 #if defined(MBEDTLS_RSA_NO_CRT)
00985         mbedtls_mpi_free( &D_blind );
00986 #else
00987         mbedtls_mpi_free( &DP_blind );
00988         mbedtls_mpi_free( &DQ_blind );
00989 #endif
00990     }
00991 
00992     mbedtls_mpi_free( &T );
00993 
00994 #if !defined(MBEDTLS_RSA_NO_CRT)
00995     mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ );
00996 #endif
00997 
00998     mbedtls_mpi_free( &C );
00999     mbedtls_mpi_free( &I );
01000 
01001     if( ret != 0 )
01002         return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret );
01003 
01004     return( 0 );
01005 }
01006 
01007 #if defined(MBEDTLS_PKCS1_V21)
01008 /**
01009  * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
01010  *
01011  * \param dst       buffer to mask
01012  * \param dlen      length of destination buffer
01013  * \param src       source of the mask generation
01014  * \param slen      length of the source buffer
01015  * \param md_ctx    message digest context to use
01016  */
01017 static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
01018                       size_t slen, mbedtls_md_context_t *md_ctx )
01019 {
01020     unsigned char mask[MBEDTLS_MD_MAX_SIZE];
01021     unsigned char counter[4];
01022     unsigned char *p;
01023     unsigned int hlen;
01024     size_t i, use_len;
01025     int ret = 0;
01026 
01027     memset( mask, 0, MBEDTLS_MD_MAX_SIZE );
01028     memset( counter, 0, 4 );
01029 
01030     hlen = mbedtls_md_get_size( md_ctx->md_info );
01031 
01032     /* Generate and apply dbMask */
01033     p = dst;
01034 
01035     while( dlen > 0 )
01036     {
01037         use_len = hlen;
01038         if( dlen < hlen )
01039             use_len = dlen;
01040 
01041         if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 )
01042             goto exit;
01043         if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 )
01044             goto exit;
01045         if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 )
01046             goto exit;
01047         if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 )
01048             goto exit;
01049 
01050         for( i = 0; i < use_len; ++i )
01051             *p++ ^= mask[i];
01052 
01053         counter[3]++;
01054 
01055         dlen -= use_len;
01056     }
01057 
01058 exit:
01059     mbedtls_platform_zeroize( mask, sizeof( mask ) );
01060 
01061     return( ret );
01062 }
01063 #endif /* MBEDTLS_PKCS1_V21 */
01064 
01065 #if defined(MBEDTLS_PKCS1_V21)
01066 /*
01067  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
01068  */
01069 int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
01070                             int (*f_rng)(void *, unsigned char *, size_t),
01071                             void *p_rng,
01072                             int mode,
01073                             const unsigned char *label, size_t label_len,
01074                             size_t ilen,
01075                             const unsigned char *input,
01076                             unsigned char *output )
01077 {
01078     size_t olen;
01079     int ret;
01080     unsigned char *p = output;
01081     unsigned int hlen;
01082     const mbedtls_md_info_t *md_info;
01083     mbedtls_md_context_t md_ctx;
01084 
01085     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V21 )
01086         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01087 
01088     if( f_rng == NULL )
01089         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01090 
01091     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id  );
01092     if( md_info == NULL )
01093         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01094 
01095     olen = ctx->len ;
01096     hlen = mbedtls_md_get_size( md_info );
01097 
01098     /* first comparison checks for overflow */
01099     if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
01100         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01101 
01102     memset( output, 0, olen );
01103 
01104     *p++ = 0;
01105 
01106     /* Generate a random octet string seed */
01107     if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
01108         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
01109 
01110     p += hlen;
01111 
01112     /* Construct DB */
01113     if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 )
01114         return( ret );
01115     p += hlen;
01116     p += olen - 2 * hlen - 2 - ilen;
01117     *p++ = 1;
01118     memcpy( p, input, ilen );
01119 
01120     mbedtls_md_init( &md_ctx );
01121     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
01122         goto exit;
01123 
01124     /* maskedDB: Apply dbMask to DB */
01125     if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
01126                           &md_ctx ) ) != 0 )
01127         goto exit;
01128 
01129     /* maskedSeed: Apply seedMask to seed */
01130     if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
01131                           &md_ctx ) ) != 0 )
01132         goto exit;
01133 
01134 exit:
01135     mbedtls_md_free( &md_ctx );
01136 
01137     if( ret != 0 )
01138         return( ret );
01139 
01140     return( ( mode == MBEDTLS_RSA_PUBLIC )
01141             ? mbedtls_rsa_public(  ctx, output, output )
01142             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
01143 }
01144 #endif /* MBEDTLS_PKCS1_V21 */
01145 
01146 #if defined(MBEDTLS_PKCS1_V15)
01147 /*
01148  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
01149  */
01150 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
01151                                  int (*f_rng)(void *, unsigned char *, size_t),
01152                                  void *p_rng,
01153                                  int mode, size_t ilen,
01154                                  const unsigned char *input,
01155                                  unsigned char *output )
01156 {
01157     size_t nb_pad, olen;
01158     int ret;
01159     unsigned char *p = output;
01160 
01161     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V15 )
01162         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01163 
01164     // We don't check p_rng because it won't be dereferenced here
01165     if( f_rng == NULL || input == NULL || output == NULL )
01166         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01167 
01168     olen = ctx->len ;
01169 
01170     /* first comparison checks for overflow */
01171     if( ilen + 11 < ilen || olen < ilen + 11 )
01172         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01173 
01174     nb_pad = olen - 3 - ilen;
01175 
01176     *p++ = 0;
01177     if( mode == MBEDTLS_RSA_PUBLIC )
01178     {
01179         *p++ = MBEDTLS_RSA_CRYPT;
01180 
01181         while( nb_pad-- > 0 )
01182         {
01183             int rng_dl = 100;
01184 
01185             do {
01186                 ret = f_rng( p_rng, p, 1 );
01187             } while( *p == 0 && --rng_dl && ret == 0 );
01188 
01189             /* Check if RNG failed to generate data */
01190             if( rng_dl == 0 || ret != 0 )
01191                 return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
01192 
01193             p++;
01194         }
01195     }
01196     else
01197     {
01198         *p++ = MBEDTLS_RSA_SIGN;
01199 
01200         while( nb_pad-- > 0 )
01201             *p++ = 0xFF;
01202     }
01203 
01204     *p++ = 0;
01205     memcpy( p, input, ilen );
01206 
01207     return( ( mode == MBEDTLS_RSA_PUBLIC )
01208             ? mbedtls_rsa_public(  ctx, output, output )
01209             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
01210 }
01211 #endif /* MBEDTLS_PKCS1_V15 */
01212 
01213 /*
01214  * Add the message padding, then do an RSA operation
01215  */
01216 int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
01217                        int (*f_rng)(void *, unsigned char *, size_t),
01218                        void *p_rng,
01219                        int mode, size_t ilen,
01220                        const unsigned char *input,
01221                        unsigned char *output )
01222 {
01223     switch( ctx->padding  )
01224     {
01225 #if defined(MBEDTLS_PKCS1_V15)
01226         case MBEDTLS_RSA_PKCS_V15:
01227             return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,
01228                                                 input, output );
01229 #endif
01230 
01231 #if defined(MBEDTLS_PKCS1_V21)
01232         case MBEDTLS_RSA_PKCS_V21:
01233             return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,
01234                                            ilen, input, output );
01235 #endif
01236 
01237         default:
01238             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
01239     }
01240 }
01241 
01242 #if defined(MBEDTLS_PKCS1_V21)
01243 /*
01244  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
01245  */
01246 int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
01247                             int (*f_rng)(void *, unsigned char *, size_t),
01248                             void *p_rng,
01249                             int mode,
01250                             const unsigned char *label, size_t label_len,
01251                             size_t *olen,
01252                             const unsigned char *input,
01253                             unsigned char *output,
01254                             size_t output_max_len )
01255 {
01256     int ret;
01257     size_t ilen, i, pad_len;
01258     unsigned char *p, bad, pad_done;
01259     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
01260     unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
01261     unsigned int hlen;
01262     const mbedtls_md_info_t *md_info;
01263     mbedtls_md_context_t md_ctx;
01264 
01265     /*
01266      * Parameters sanity checks
01267      */
01268     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V21 )
01269         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01270 
01271     ilen = ctx->len ;
01272 
01273     if( ilen < 16 || ilen > sizeof( buf ) )
01274         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01275 
01276     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id  );
01277     if( md_info == NULL )
01278         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01279 
01280     hlen = mbedtls_md_get_size( md_info );
01281 
01282     // checking for integer underflow
01283     if( 2 * hlen + 2 > ilen )
01284         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01285 
01286     /*
01287      * RSA operation
01288      */
01289     ret = ( mode == MBEDTLS_RSA_PUBLIC )
01290           ? mbedtls_rsa_public(  ctx, input, buf )
01291           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
01292 
01293     if( ret != 0 )
01294         goto cleanup;
01295 
01296     /*
01297      * Unmask data and generate lHash
01298      */
01299     mbedtls_md_init( &md_ctx );
01300     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
01301     {
01302         mbedtls_md_free( &md_ctx );
01303         goto cleanup;
01304     }
01305 
01306     /* seed: Apply seedMask to maskedSeed */
01307     if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
01308                           &md_ctx ) ) != 0 ||
01309     /* DB: Apply dbMask to maskedDB */
01310         ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
01311                           &md_ctx ) ) != 0 )
01312     {
01313         mbedtls_md_free( &md_ctx );
01314         goto cleanup;
01315     }
01316 
01317     mbedtls_md_free( &md_ctx );
01318 
01319     /* Generate lHash */
01320     if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 )
01321         goto cleanup;
01322 
01323     /*
01324      * Check contents, in "constant-time"
01325      */
01326     p = buf;
01327     bad = 0;
01328 
01329     bad |= *p++; /* First byte must be 0 */
01330 
01331     p += hlen; /* Skip seed */
01332 
01333     /* Check lHash */
01334     for( i = 0; i < hlen; i++ )
01335         bad |= lhash[i] ^ *p++;
01336 
01337     /* Get zero-padding len, but always read till end of buffer
01338      * (minus one, for the 01 byte) */
01339     pad_len = 0;
01340     pad_done = 0;
01341     for( i = 0; i < ilen - 2 * hlen - 2; i++ )
01342     {
01343         pad_done |= p[i];
01344         pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
01345     }
01346 
01347     p += pad_len;
01348     bad |= *p++ ^ 0x01;
01349 
01350     /*
01351      * The only information "leaked" is whether the padding was correct or not
01352      * (eg, no data is copied if it was not correct). This meets the
01353      * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
01354      * the different error conditions.
01355      */
01356     if( bad != 0 )
01357     {
01358         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
01359         goto cleanup;
01360     }
01361 
01362     if( ilen - ( p - buf ) > output_max_len )
01363     {
01364         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
01365         goto cleanup;
01366     }
01367 
01368     *olen = ilen - (p - buf);
01369     memcpy( output, p, *olen );
01370     ret = 0;
01371 
01372 cleanup:
01373     mbedtls_platform_zeroize( buf, sizeof( buf ) );
01374     mbedtls_platform_zeroize( lhash, sizeof( lhash ) );
01375 
01376     return( ret );
01377 }
01378 #endif /* MBEDTLS_PKCS1_V21 */
01379 
01380 #if defined(MBEDTLS_PKCS1_V15)
01381 /*
01382  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
01383  */
01384 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
01385                                  int (*f_rng)(void *, unsigned char *, size_t),
01386                                  void *p_rng,
01387                                  int mode, size_t *olen,
01388                                  const unsigned char *input,
01389                                  unsigned char *output,
01390                                  size_t output_max_len)
01391 {
01392     int ret;
01393     size_t ilen, pad_count = 0, i;
01394     unsigned char *p, bad, pad_done = 0;
01395     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
01396 
01397     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V15 )
01398         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01399 
01400     ilen = ctx->len ;
01401 
01402     if( ilen < 16 || ilen > sizeof( buf ) )
01403         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01404 
01405     ret = ( mode == MBEDTLS_RSA_PUBLIC )
01406           ? mbedtls_rsa_public(  ctx, input, buf )
01407           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
01408 
01409     if( ret != 0 )
01410         goto cleanup;
01411 
01412     p = buf;
01413     bad = 0;
01414 
01415     /*
01416      * Check and get padding len in "constant-time"
01417      */
01418     bad |= *p++; /* First byte must be 0 */
01419 
01420     /* This test does not depend on secret data */
01421     if( mode == MBEDTLS_RSA_PRIVATE )
01422     {
01423         bad |= *p++ ^ MBEDTLS_RSA_CRYPT;
01424 
01425         /* Get padding len, but always read till end of buffer
01426          * (minus one, for the 00 byte) */
01427         for( i = 0; i < ilen - 3; i++ )
01428         {
01429             pad_done  |= ((p[i] | (unsigned char)-p[i]) >> 7) ^ 1;
01430             pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
01431         }
01432 
01433         p += pad_count;
01434         bad |= *p++; /* Must be zero */
01435     }
01436     else
01437     {
01438         bad |= *p++ ^ MBEDTLS_RSA_SIGN;
01439 
01440         /* Get padding len, but always read till end of buffer
01441          * (minus one, for the 00 byte) */
01442         for( i = 0; i < ilen - 3; i++ )
01443         {
01444             pad_done |= ( p[i] != 0xFF );
01445             pad_count += ( pad_done == 0 );
01446         }
01447 
01448         p += pad_count;
01449         bad |= *p++; /* Must be zero */
01450     }
01451 
01452     bad |= ( pad_count < 8 );
01453 
01454     if( bad )
01455     {
01456         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
01457         goto cleanup;
01458     }
01459 
01460     if( ilen - ( p - buf ) > output_max_len )
01461     {
01462         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
01463         goto cleanup;
01464     }
01465 
01466     *olen = ilen - (p - buf);
01467     memcpy( output, p, *olen );
01468     ret = 0;
01469 
01470 cleanup:
01471     mbedtls_platform_zeroize( buf, sizeof( buf ) );
01472 
01473     return( ret );
01474 }
01475 #endif /* MBEDTLS_PKCS1_V15 */
01476 
01477 /*
01478  * Do an RSA operation, then remove the message padding
01479  */
01480 int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
01481                        int (*f_rng)(void *, unsigned char *, size_t),
01482                        void *p_rng,
01483                        int mode, size_t *olen,
01484                        const unsigned char *input,
01485                        unsigned char *output,
01486                        size_t output_max_len)
01487 {
01488     switch( ctx->padding  )
01489     {
01490 #if defined(MBEDTLS_PKCS1_V15)
01491         case MBEDTLS_RSA_PKCS_V15:
01492             return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,
01493                                                 input, output, output_max_len );
01494 #endif
01495 
01496 #if defined(MBEDTLS_PKCS1_V21)
01497         case MBEDTLS_RSA_PKCS_V21:
01498             return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,
01499                                            olen, input, output,
01500                                            output_max_len );
01501 #endif
01502 
01503         default:
01504             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
01505     }
01506 }
01507 
01508 #if defined(MBEDTLS_PKCS1_V21)
01509 /*
01510  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
01511  */
01512 int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
01513                          int (*f_rng)(void *, unsigned char *, size_t),
01514                          void *p_rng,
01515                          int mode,
01516                          mbedtls_md_type_t md_alg,
01517                          unsigned int hashlen,
01518                          const unsigned char *hash,
01519                          unsigned char *sig )
01520 {
01521     size_t olen;
01522     unsigned char *p = sig;
01523     unsigned char salt[MBEDTLS_MD_MAX_SIZE];
01524     unsigned int slen, hlen, offset = 0;
01525     int ret;
01526     size_t msb;
01527     const mbedtls_md_info_t *md_info;
01528     mbedtls_md_context_t md_ctx;
01529 
01530     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V21 )
01531         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01532 
01533     if( f_rng == NULL )
01534         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01535 
01536     olen = ctx->len ;
01537 
01538     if( md_alg != MBEDTLS_MD_NONE )
01539     {
01540         /* Gather length of hash to sign */
01541         md_info = mbedtls_md_info_from_type( md_alg );
01542         if( md_info == NULL )
01543             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01544 
01545         hashlen = mbedtls_md_get_size( md_info );
01546     }
01547 
01548     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id  );
01549     if( md_info == NULL )
01550         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01551 
01552     hlen = mbedtls_md_get_size( md_info );
01553     slen = hlen;
01554 
01555     if( olen < hlen + slen + 2 )
01556         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01557 
01558     memset( sig, 0, olen );
01559 
01560     /* Generate salt of length slen */
01561     if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
01562         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
01563 
01564     /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
01565     msb = mbedtls_mpi_bitlen( &ctx->N  ) - 1;
01566     p += olen - hlen * 2 - 2;
01567     *p++ = 0x01;
01568     memcpy( p, salt, slen );
01569     p += slen;
01570 
01571     mbedtls_md_init( &md_ctx );
01572     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
01573         goto exit;
01574 
01575     /* Generate H = Hash( M' ) */
01576     if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )
01577         goto exit;
01578     if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 )
01579         goto exit;
01580     if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 )
01581         goto exit;
01582     if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 )
01583         goto exit;
01584     if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 )
01585         goto exit;
01586 
01587     /* Compensate for boundary condition when applying mask */
01588     if( msb % 8 == 0 )
01589         offset = 1;
01590 
01591     /* maskedDB: Apply dbMask to DB */
01592     if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen,
01593                           &md_ctx ) ) != 0 )
01594         goto exit;
01595 
01596     msb = mbedtls_mpi_bitlen( &ctx->N  ) - 1;
01597     sig[0] &= 0xFF >> ( olen * 8 - msb );
01598 
01599     p += hlen;
01600     *p++ = 0xBC;
01601 
01602     mbedtls_platform_zeroize( salt, sizeof( salt ) );
01603 
01604 exit:
01605     mbedtls_md_free( &md_ctx );
01606 
01607     if( ret != 0 )
01608         return( ret );
01609 
01610     return( ( mode == MBEDTLS_RSA_PUBLIC )
01611             ? mbedtls_rsa_public(  ctx, sig, sig )
01612             : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) );
01613 }
01614 #endif /* MBEDTLS_PKCS1_V21 */
01615 
01616 #if defined(MBEDTLS_PKCS1_V15)
01617 /*
01618  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
01619  */
01620 
01621 /* Construct a PKCS v1.5 encoding of a hashed message
01622  *
01623  * This is used both for signature generation and verification.
01624  *
01625  * Parameters:
01626  * - md_alg:  Identifies the hash algorithm used to generate the given hash;
01627  *            MBEDTLS_MD_NONE if raw data is signed.
01628  * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.
01629  * - hash:    Buffer containing the hashed message or the raw data.
01630  * - dst_len: Length of the encoded message.
01631  * - dst:     Buffer to hold the encoded message.
01632  *
01633  * Assumptions:
01634  * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.
01635  * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.
01636  * - dst points to a buffer of size at least dst_len.
01637  *
01638  */
01639 static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg,
01640                                         unsigned int hashlen,
01641                                         const unsigned char *hash,
01642                                         size_t dst_len,
01643                                         unsigned char *dst )
01644 {
01645     size_t oid_size  = 0;
01646     size_t nb_pad    = dst_len;
01647     unsigned char *p = dst;
01648     const char *oid  = NULL;
01649 
01650     /* Are we signing hashed or raw data? */
01651     if( md_alg != MBEDTLS_MD_NONE )
01652     {
01653         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
01654         if( md_info == NULL )
01655             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01656 
01657         if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
01658             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01659 
01660         hashlen = mbedtls_md_get_size( md_info );
01661 
01662         /* Double-check that 8 + hashlen + oid_size can be used as a
01663          * 1-byte ASN.1 length encoding and that there's no overflow. */
01664         if( 8 + hashlen + oid_size  >= 0x80         ||
01665             10 + hashlen            <  hashlen      ||
01666             10 + hashlen + oid_size <  10 + hashlen )
01667             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01668 
01669         /*
01670          * Static bounds check:
01671          * - Need 10 bytes for five tag-length pairs.
01672          *   (Insist on 1-byte length encodings to protect against variants of
01673          *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
01674          * - Need hashlen bytes for hash
01675          * - Need oid_size bytes for hash alg OID.
01676          */
01677         if( nb_pad < 10 + hashlen + oid_size )
01678             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01679         nb_pad -= 10 + hashlen + oid_size;
01680     }
01681     else
01682     {
01683         if( nb_pad < hashlen )
01684             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01685 
01686         nb_pad -= hashlen;
01687     }
01688 
01689     /* Need space for signature header and padding delimiter (3 bytes),
01690      * and 8 bytes for the minimal padding */
01691     if( nb_pad < 3 + 8 )
01692         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01693     nb_pad -= 3;
01694 
01695     /* Now nb_pad is the amount of memory to be filled
01696      * with padding, and at least 8 bytes long. */
01697 
01698     /* Write signature header and padding */
01699     *p++ = 0;
01700     *p++ = MBEDTLS_RSA_SIGN;
01701     memset( p, 0xFF, nb_pad );
01702     p += nb_pad;
01703     *p++ = 0;
01704 
01705     /* Are we signing raw data? */
01706     if( md_alg == MBEDTLS_MD_NONE )
01707     {
01708         memcpy( p, hash, hashlen );
01709         return( 0 );
01710     }
01711 
01712     /* Signing hashed data, add corresponding ASN.1 structure
01713      *
01714      * DigestInfo ::= SEQUENCE {
01715      *   digestAlgorithm DigestAlgorithmIdentifier,
01716      *   digest Digest }
01717      * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
01718      * Digest ::= OCTET STRING
01719      *
01720      * Schematic:
01721      * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
01722      *                                 TAG-NULL + LEN [ NULL ] ]
01723      *                 TAG-OCTET + LEN [ HASH ] ]
01724      */
01725     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
01726     *p++ = (unsigned char)( 0x08 + oid_size + hashlen );
01727     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
01728     *p++ = (unsigned char)( 0x04 + oid_size );
01729     *p++ = MBEDTLS_ASN1_OID;
01730     *p++ = (unsigned char) oid_size;
01731     memcpy( p, oid, oid_size );
01732     p += oid_size;
01733     *p++ = MBEDTLS_ASN1_NULL;
01734     *p++ = 0x00;
01735     *p++ = MBEDTLS_ASN1_OCTET_STRING;
01736     *p++ = (unsigned char) hashlen;
01737     memcpy( p, hash, hashlen );
01738     p += hashlen;
01739 
01740     /* Just a sanity-check, should be automatic
01741      * after the initial bounds check. */
01742     if( p != dst + dst_len )
01743     {
01744         mbedtls_platform_zeroize( dst, dst_len );
01745         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01746     }
01747 
01748     return( 0 );
01749 }
01750 
01751 /*
01752  * Do an RSA operation to sign the message digest
01753  */
01754 int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
01755                                int (*f_rng)(void *, unsigned char *, size_t),
01756                                void *p_rng,
01757                                int mode,
01758                                mbedtls_md_type_t md_alg,
01759                                unsigned int hashlen,
01760                                const unsigned char *hash,
01761                                unsigned char *sig )
01762 {
01763     int ret;
01764     unsigned char *sig_try = NULL, *verif = NULL;
01765 
01766     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V15 )
01767         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01768 
01769     /*
01770      * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
01771      */
01772 
01773     if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash,
01774                                              ctx->len , sig ) ) != 0 )
01775         return( ret );
01776 
01777     /*
01778      * Call respective RSA primitive
01779      */
01780 
01781     if( mode == MBEDTLS_RSA_PUBLIC )
01782     {
01783         /* Skip verification on a public key operation */
01784         return( mbedtls_rsa_public( ctx, sig, sig ) );
01785     }
01786 
01787     /* Private key operation
01788      *
01789      * In order to prevent Lenstra's attack, make the signature in a
01790      * temporary buffer and check it before returning it.
01791      */
01792 
01793     sig_try = mbedtls_calloc( 1, ctx->len  );
01794     if( sig_try == NULL )
01795         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
01796 
01797     verif = mbedtls_calloc( 1, ctx->len  );
01798     if( verif == NULL )
01799     {
01800         mbedtls_free( sig_try );
01801         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
01802     }
01803 
01804     MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) );
01805     MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) );
01806 
01807     if( mbedtls_safer_memcmp( verif, sig, ctx->len  ) != 0 )
01808     {
01809         ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
01810         goto cleanup;
01811     }
01812 
01813     memcpy( sig, sig_try, ctx->len  );
01814 
01815 cleanup:
01816     mbedtls_free( sig_try );
01817     mbedtls_free( verif );
01818 
01819     return( ret );
01820 }
01821 #endif /* MBEDTLS_PKCS1_V15 */
01822 
01823 /*
01824  * Do an RSA operation to sign the message digest
01825  */
01826 int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
01827                     int (*f_rng)(void *, unsigned char *, size_t),
01828                     void *p_rng,
01829                     int mode,
01830                     mbedtls_md_type_t md_alg,
01831                     unsigned int hashlen,
01832                     const unsigned char *hash,
01833                     unsigned char *sig )
01834 {
01835     switch( ctx->padding  )
01836     {
01837 #if defined(MBEDTLS_PKCS1_V15)
01838         case MBEDTLS_RSA_PKCS_V15:
01839             return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,
01840                                               hashlen, hash, sig );
01841 #endif
01842 
01843 #if defined(MBEDTLS_PKCS1_V21)
01844         case MBEDTLS_RSA_PKCS_V21:
01845             return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
01846                                         hashlen, hash, sig );
01847 #endif
01848 
01849         default:
01850             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
01851     }
01852 }
01853 
01854 #if defined(MBEDTLS_PKCS1_V21)
01855 /*
01856  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
01857  */
01858 int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
01859                                int (*f_rng)(void *, unsigned char *, size_t),
01860                                void *p_rng,
01861                                int mode,
01862                                mbedtls_md_type_t md_alg,
01863                                unsigned int hashlen,
01864                                const unsigned char *hash,
01865                                mbedtls_md_type_t mgf1_hash_id,
01866                                int expected_salt_len,
01867                                const unsigned char *sig )
01868 {
01869     int ret;
01870     size_t siglen;
01871     unsigned char *p;
01872     unsigned char *hash_start;
01873     unsigned char result[MBEDTLS_MD_MAX_SIZE];
01874     unsigned char zeros[8];
01875     unsigned int hlen;
01876     size_t observed_salt_len, msb;
01877     const mbedtls_md_info_t *md_info;
01878     mbedtls_md_context_t md_ctx;
01879     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
01880 
01881     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V21 )
01882         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01883 
01884     siglen = ctx->len ;
01885 
01886     if( siglen < 16 || siglen > sizeof( buf ) )
01887         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01888 
01889     ret = ( mode == MBEDTLS_RSA_PUBLIC )
01890           ? mbedtls_rsa_public(  ctx, sig, buf )
01891           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );
01892 
01893     if( ret != 0 )
01894         return( ret );
01895 
01896     p = buf;
01897 
01898     if( buf[siglen - 1] != 0xBC )
01899         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
01900 
01901     if( md_alg != MBEDTLS_MD_NONE )
01902     {
01903         /* Gather length of hash to sign */
01904         md_info = mbedtls_md_info_from_type( md_alg );
01905         if( md_info == NULL )
01906             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01907 
01908         hashlen = mbedtls_md_get_size( md_info );
01909     }
01910 
01911     md_info = mbedtls_md_info_from_type( mgf1_hash_id );
01912     if( md_info == NULL )
01913         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01914 
01915     hlen = mbedtls_md_get_size( md_info );
01916 
01917     memset( zeros, 0, 8 );
01918 
01919     /*
01920      * Note: EMSA-PSS verification is over the length of N - 1 bits
01921      */
01922     msb = mbedtls_mpi_bitlen( &ctx->N  ) - 1;
01923 
01924     if( buf[0] >> ( 8 - siglen * 8 + msb ) )
01925         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01926 
01927     /* Compensate for boundary condition when applying mask */
01928     if( msb % 8 == 0 )
01929     {
01930         p++;
01931         siglen -= 1;
01932     }
01933 
01934     if( siglen < hlen + 2 )
01935         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
01936     hash_start = p + siglen - hlen - 1;
01937 
01938     mbedtls_md_init( &md_ctx );
01939     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
01940         goto exit;
01941 
01942     ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx );
01943     if( ret != 0 )
01944         goto exit;
01945 
01946     buf[0] &= 0xFF >> ( siglen * 8 - msb );
01947 
01948     while( p < hash_start - 1 && *p == 0 )
01949         p++;
01950 
01951     if( *p++ != 0x01 )
01952     {
01953         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
01954         goto exit;
01955     }
01956 
01957     observed_salt_len = hash_start - p;
01958 
01959     if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
01960         observed_salt_len != (size_t) expected_salt_len )
01961     {
01962         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
01963         goto exit;
01964     }
01965 
01966     /*
01967      * Generate H = Hash( M' )
01968      */
01969     ret = mbedtls_md_starts( &md_ctx );
01970     if ( ret != 0 )
01971         goto exit;
01972     ret = mbedtls_md_update( &md_ctx, zeros, 8 );
01973     if ( ret != 0 )
01974         goto exit;
01975     ret = mbedtls_md_update( &md_ctx, hash, hashlen );
01976     if ( ret != 0 )
01977         goto exit;
01978     ret = mbedtls_md_update( &md_ctx, p, observed_salt_len );
01979     if ( ret != 0 )
01980         goto exit;
01981     ret = mbedtls_md_finish( &md_ctx, result );
01982     if ( ret != 0 )
01983         goto exit;
01984 
01985     if( memcmp( hash_start, result, hlen ) != 0 )
01986     {
01987         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
01988         goto exit;
01989     }
01990 
01991 exit:
01992     mbedtls_md_free( &md_ctx );
01993 
01994     return( ret );
01995 }
01996 
01997 /*
01998  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
01999  */
02000 int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
02001                            int (*f_rng)(void *, unsigned char *, size_t),
02002                            void *p_rng,
02003                            int mode,
02004                            mbedtls_md_type_t md_alg,
02005                            unsigned int hashlen,
02006                            const unsigned char *hash,
02007                            const unsigned char *sig )
02008 {
02009     mbedtls_md_type_t mgf1_hash_id = ( ctx->hash_id  != MBEDTLS_MD_NONE )
02010                              ? (mbedtls_md_type_t) ctx->hash_id 
02011                              : md_alg;
02012 
02013     return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,
02014                                        md_alg, hashlen, hash,
02015                                        mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,
02016                                        sig ) );
02017 
02018 }
02019 #endif /* MBEDTLS_PKCS1_V21 */
02020 
02021 #if defined(MBEDTLS_PKCS1_V15)
02022 /*
02023  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
02024  */
02025 int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
02026                                  int (*f_rng)(void *, unsigned char *, size_t),
02027                                  void *p_rng,
02028                                  int mode,
02029                                  mbedtls_md_type_t md_alg,
02030                                  unsigned int hashlen,
02031                                  const unsigned char *hash,
02032                                  const unsigned char *sig )
02033 {
02034     int ret = 0;
02035     const size_t sig_len = ctx->len ;
02036     unsigned char *encoded = NULL, *encoded_expected = NULL;
02037 
02038     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding  != MBEDTLS_RSA_PKCS_V15 )
02039         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
02040 
02041     /*
02042      * Prepare expected PKCS1 v1.5 encoding of hash.
02043      */
02044 
02045     if( ( encoded          = mbedtls_calloc( 1, sig_len ) ) == NULL ||
02046         ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL )
02047     {
02048         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
02049         goto cleanup;
02050     }
02051 
02052     if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len,
02053                                              encoded_expected ) ) != 0 )
02054         goto cleanup;
02055 
02056     /*
02057      * Apply RSA primitive to get what should be PKCS1 encoded hash.
02058      */
02059 
02060     ret = ( mode == MBEDTLS_RSA_PUBLIC )
02061           ? mbedtls_rsa_public(  ctx, sig, encoded )
02062           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded );
02063     if( ret != 0 )
02064         goto cleanup;
02065 
02066     /*
02067      * Compare
02068      */
02069 
02070     if( ( ret = mbedtls_safer_memcmp( encoded, encoded_expected,
02071                                       sig_len ) ) != 0 )
02072     {
02073         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
02074         goto cleanup;
02075     }
02076 
02077 cleanup:
02078 
02079     if( encoded != NULL )
02080     {
02081         mbedtls_platform_zeroize( encoded, sig_len );
02082         mbedtls_free( encoded );
02083     }
02084 
02085     if( encoded_expected != NULL )
02086     {
02087         mbedtls_platform_zeroize( encoded_expected, sig_len );
02088         mbedtls_free( encoded_expected );
02089     }
02090 
02091     return( ret );
02092 }
02093 #endif /* MBEDTLS_PKCS1_V15 */
02094 
02095 /*
02096  * Do an RSA operation and check the message digest
02097  */
02098 int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
02099                       int (*f_rng)(void *, unsigned char *, size_t),
02100                       void *p_rng,
02101                       int mode,
02102                       mbedtls_md_type_t md_alg,
02103                       unsigned int hashlen,
02104                       const unsigned char *hash,
02105                       const unsigned char *sig )
02106 {
02107     switch( ctx->padding  )
02108     {
02109 #if defined(MBEDTLS_PKCS1_V15)
02110         case MBEDTLS_RSA_PKCS_V15:
02111             return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,
02112                                                 hashlen, hash, sig );
02113 #endif
02114 
02115 #if defined(MBEDTLS_PKCS1_V21)
02116         case MBEDTLS_RSA_PKCS_V21:
02117             return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,
02118                                           hashlen, hash, sig );
02119 #endif
02120 
02121         default:
02122             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
02123     }
02124 }
02125 
02126 /*
02127  * Copy the components of an RSA key
02128  */
02129 int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
02130 {
02131     int ret;
02132 
02133     dst->ver  = src->ver ;
02134     dst->len  = src->len ;
02135 
02136     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N , &src->N  ) );
02137     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E , &src->E  ) );
02138 
02139     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D , &src->D  ) );
02140     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P , &src->P  ) );
02141     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q , &src->Q  ) );
02142 
02143 #if !defined(MBEDTLS_RSA_NO_CRT)
02144     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP , &src->DP  ) );
02145     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ , &src->DQ  ) );
02146     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP , &src->QP  ) );
02147     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP , &src->RP  ) );
02148     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ , &src->RQ  ) );
02149 #endif
02150 
02151     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN , &src->RN  ) );
02152 
02153     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi , &src->Vi  ) );
02154     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf , &src->Vf  ) );
02155 
02156     dst->padding  = src->padding ;
02157     dst->hash_id  = src->hash_id ;
02158 
02159 cleanup:
02160     if( ret != 0 )
02161         mbedtls_rsa_free( dst );
02162 
02163     return( ret );
02164 }
02165 
02166 /*
02167  * Free the components of an RSA key
02168  */
02169 void mbedtls_rsa_free( mbedtls_rsa_context *ctx )
02170 {
02171     mbedtls_mpi_free( &ctx->Vi  ); mbedtls_mpi_free( &ctx->Vf  );
02172     mbedtls_mpi_free( &ctx->RN  ); mbedtls_mpi_free( &ctx->D   );
02173     mbedtls_mpi_free( &ctx->Q   ); mbedtls_mpi_free( &ctx->P   );
02174     mbedtls_mpi_free( &ctx->E   ); mbedtls_mpi_free( &ctx->N   );
02175 
02176 #if !defined(MBEDTLS_RSA_NO_CRT)
02177     mbedtls_mpi_free( &ctx->RQ  ); mbedtls_mpi_free( &ctx->RP  );
02178     mbedtls_mpi_free( &ctx->QP  ); mbedtls_mpi_free( &ctx->DQ  );
02179     mbedtls_mpi_free( &ctx->DP  );
02180 #endif /* MBEDTLS_RSA_NO_CRT */
02181 
02182 #if defined(MBEDTLS_THREADING_C)
02183     mbedtls_mutex_free( &ctx->mutex  );
02184 #endif
02185 }
02186 
02187 #endif /* !MBEDTLS_RSA_ALT */
02188 
02189 #if defined(MBEDTLS_SELF_TEST)
02190 
02191 #include "mbedtls/sha1.h"
02192 
02193 /*
02194  * Example RSA-1024 keypair, for test purposes
02195  */
02196 #define KEY_LEN 128
02197 
02198 #define RSA_N   "9292758453063D803DD603D5E777D788" \
02199                 "8ED1D5BF35786190FA2F23EBC0848AEA" \
02200                 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
02201                 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
02202                 "93A89813FBF3C4F8066D2D800F7C38A8" \
02203                 "1AE31942917403FF4946B0A83D3D3E05" \
02204                 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
02205                 "5E94BB77B07507233A0BC7BAC8F90F79"
02206 
02207 #define RSA_E   "10001"
02208 
02209 #define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
02210                 "66CA472BC44D253102F8B4A9D3BFA750" \
02211                 "91386C0077937FE33FA3252D28855837" \
02212                 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
02213                 "DF79C5CE07EE72C7F123142198164234" \
02214                 "CABB724CF78B8173B9F880FC86322407" \
02215                 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
02216                 "071513A1E85B5DFA031F21ECAE91A34D"
02217 
02218 #define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
02219                 "2C01CAD19EA484A87EA4377637E75500" \
02220                 "FCB2005C5C7DD6EC4AC023CDA285D796" \
02221                 "C3D9E75E1EFC42488BB4F1D13AC30A57"
02222 
02223 #define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
02224                 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
02225                 "910E4168387E3C30AA1E00C339A79508" \
02226                 "8452DD96A9A5EA5D9DCA68DA636032AF"
02227 
02228 #define PT_LEN  24
02229 #define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
02230                 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
02231 
02232 #if defined(MBEDTLS_PKCS1_V15)
02233 static int myrand( void *rng_state, unsigned char *output, size_t len )
02234 {
02235 #if !defined(__OpenBSD__)
02236     size_t i;
02237 
02238     if( rng_state != NULL )
02239         rng_state  = NULL;
02240 
02241     for( i = 0; i < len; ++i )
02242         output[i] = rand();
02243 #else
02244     if( rng_state != NULL )
02245         rng_state = NULL;
02246 
02247     arc4random_buf( output, len );
02248 #endif /* !OpenBSD */
02249 
02250     return( 0 );
02251 }
02252 #endif /* MBEDTLS_PKCS1_V15 */
02253 
02254 /*
02255  * Checkup routine
02256  */
02257 int mbedtls_rsa_self_test( int verbose )
02258 {
02259     int ret = 0;
02260 #if defined(MBEDTLS_PKCS1_V15)
02261     size_t len;
02262     mbedtls_rsa_context rsa;
02263     unsigned char rsa_plaintext[PT_LEN];
02264     unsigned char rsa_decrypted[PT_LEN];
02265     unsigned char rsa_ciphertext[KEY_LEN];
02266 #if defined(MBEDTLS_SHA1_C)
02267     unsigned char sha1sum[20];
02268 #endif
02269 
02270     mbedtls_mpi K;
02271 
02272     mbedtls_mpi_init( &K );
02273     mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
02274 
02275     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N  ) );
02276     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) );
02277     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P  ) );
02278     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) );
02279     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q  ) );
02280     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) );
02281     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D  ) );
02282     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) );
02283     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E  ) );
02284     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) );
02285 
02286     MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) );
02287 
02288     if( verbose != 0 )
02289         mbedtls_printf( "  RSA key validation: " );
02290 
02291     if( mbedtls_rsa_check_pubkey(  &rsa ) != 0 ||
02292         mbedtls_rsa_check_privkey( &rsa ) != 0 )
02293     {
02294         if( verbose != 0 )
02295             mbedtls_printf( "failed\n" );
02296 
02297         ret = 1;
02298         goto cleanup;
02299     }
02300 
02301     if( verbose != 0 )
02302         mbedtls_printf( "passed\n  PKCS#1 encryption : " );
02303 
02304     memcpy( rsa_plaintext, RSA_PT, PT_LEN );
02305 
02306     if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC,
02307                                    PT_LEN, rsa_plaintext,
02308                                    rsa_ciphertext ) != 0 )
02309     {
02310         if( verbose != 0 )
02311             mbedtls_printf( "failed\n" );
02312 
02313         ret = 1;
02314         goto cleanup;
02315     }
02316 
02317     if( verbose != 0 )
02318         mbedtls_printf( "passed\n  PKCS#1 decryption : " );
02319 
02320     if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE,
02321                                    &len, rsa_ciphertext, rsa_decrypted,
02322                                    sizeof(rsa_decrypted) ) != 0 )
02323     {
02324         if( verbose != 0 )
02325             mbedtls_printf( "failed\n" );
02326 
02327         ret = 1;
02328         goto cleanup;
02329     }
02330 
02331     if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
02332     {
02333         if( verbose != 0 )
02334             mbedtls_printf( "failed\n" );
02335 
02336         ret = 1;
02337         goto cleanup;
02338     }
02339 
02340     if( verbose != 0 )
02341         mbedtls_printf( "passed\n" );
02342 
02343 #if defined(MBEDTLS_SHA1_C)
02344     if( verbose != 0 )
02345         mbedtls_printf( "  PKCS#1 data sign  : " );
02346 
02347     if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 )
02348     {
02349         if( verbose != 0 )
02350             mbedtls_printf( "failed\n" );
02351 
02352         return( 1 );
02353     }
02354 
02355     if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL,
02356                                 MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
02357                                 sha1sum, rsa_ciphertext ) != 0 )
02358     {
02359         if( verbose != 0 )
02360             mbedtls_printf( "failed\n" );
02361 
02362         ret = 1;
02363         goto cleanup;
02364     }
02365 
02366     if( verbose != 0 )
02367         mbedtls_printf( "passed\n  PKCS#1 sig. verify: " );
02368 
02369     if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL,
02370                                   MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
02371                                   sha1sum, rsa_ciphertext ) != 0 )
02372     {
02373         if( verbose != 0 )
02374             mbedtls_printf( "failed\n" );
02375 
02376         ret = 1;
02377         goto cleanup;
02378     }
02379 
02380     if( verbose != 0 )
02381         mbedtls_printf( "passed\n" );
02382 #endif /* MBEDTLS_SHA1_C */
02383 
02384     if( verbose != 0 )
02385         mbedtls_printf( "\n" );
02386 
02387 cleanup:
02388     mbedtls_mpi_free( &K );
02389     mbedtls_rsa_free( &rsa );
02390 #else /* MBEDTLS_PKCS1_V15 */
02391     ((void) verbose);
02392 #endif /* MBEDTLS_PKCS1_V15 */
02393     return( ret );
02394 }
02395 
02396 #endif /* MBEDTLS_SELF_TEST */
02397 
02398 #endif /* MBEDTLS_RSA_C */