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