mbed TLS library

Dependents:   HTTPClient-SSL WS_SERVER

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-2014, ARM Limited, All Rights Reserved
00005  *
00006  *  This file is part of mbed TLS (https://tls.mbed.org)
00007  *
00008  *  This program is free software; you can redistribute it and/or modify
00009  *  it under the terms of the GNU General Public License as published by
00010  *  the Free Software Foundation; either version 2 of the License, or
00011  *  (at your option) any later version.
00012  *
00013  *  This program is distributed in the hope that it will be useful,
00014  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  *  GNU General Public License for more details.
00017  *
00018  *  You should have received a copy of the GNU General Public License along
00019  *  with this program; if not, write to the Free Software Foundation, Inc.,
00020  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00021  */
00022 /*
00023  *  RSA was designed by Ron Rivest, Adi Shamir and Len Adleman.
00024  *
00025  *  http://theory.lcs.mit.edu/~rivest/rsapaper.pdf
00026  *  http://www.cacr.math.uwaterloo.ca/hac/about/chap8.pdf
00027  */
00028 
00029 #if !defined(POLARSSL_CONFIG_FILE)
00030 #include "polarssl/config.h"
00031 #else
00032 #include POLARSSL_CONFIG_FILE
00033 #endif
00034 
00035 #if defined(POLARSSL_RSA_C)
00036 
00037 #include "polarssl/rsa.h"
00038 #include "polarssl/oid.h"
00039 
00040 #include <string.h>
00041 
00042 #if defined(POLARSSL_PKCS1_V21)
00043 #include "polarssl/md.h"
00044 #endif
00045 
00046 #if defined(POLARSSL_PKCS1_V15) && !defined(__OpenBSD__)
00047 #include <stdlib.h>
00048 #endif
00049 
00050 #if defined(POLARSSL_PLATFORM_C)
00051 #include "polarssl/platform.h"
00052 #else
00053 #include <stdio.h>
00054 #define polarssl_printf printf
00055 #endif
00056 
00057 /*
00058  * Initialize an RSA context
00059  */
00060 void rsa_init( rsa_context *ctx,
00061                int padding,
00062                int hash_id )
00063 {
00064     memset( ctx, 0, sizeof( rsa_context ) );
00065 
00066     rsa_set_padding( ctx, padding, hash_id );
00067 
00068 #if defined(POLARSSL_THREADING_C)
00069     polarssl_mutex_init( &ctx->mutex  );
00070 #endif
00071 }
00072 
00073 /*
00074  * Set padding for an existing RSA context
00075  */
00076 void rsa_set_padding( rsa_context *ctx, int padding, int hash_id )
00077 {
00078     ctx->padding  = padding;
00079     ctx->hash_id  = hash_id;
00080 }
00081 
00082 #if defined(POLARSSL_GENPRIME)
00083 
00084 /*
00085  * Generate an RSA keypair
00086  */
00087 int rsa_gen_key( rsa_context *ctx,
00088                  int (*f_rng)(void *, unsigned char *, size_t),
00089                  void *p_rng,
00090                  unsigned int nbits, int exponent )
00091 {
00092     int ret;
00093     mpi P1, Q1, H, G;
00094 
00095     if( f_rng == NULL || nbits < 128 || exponent < 3 )
00096         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00097 
00098     mpi_init( &P1 ); mpi_init( &Q1 ); mpi_init( &H ); mpi_init( &G );
00099 
00100     /*
00101      * find primes P and Q with Q < P so that:
00102      * GCD( E, (P-1)*(Q-1) ) == 1
00103      */
00104     MPI_CHK( mpi_lset( &ctx->E , exponent ) );
00105 
00106     do
00107     {
00108         MPI_CHK( mpi_gen_prime( &ctx->P , ( nbits + 1 ) >> 1, 0,
00109                                 f_rng, p_rng ) );
00110 
00111         MPI_CHK( mpi_gen_prime( &ctx->Q , ( nbits + 1 ) >> 1, 0,
00112                                 f_rng, p_rng ) );
00113 
00114         if( mpi_cmp_mpi( &ctx->P , &ctx->Q  ) < 0 )
00115             mpi_swap( &ctx->P , &ctx->Q  );
00116 
00117         if( mpi_cmp_mpi( &ctx->P , &ctx->Q  ) == 0 )
00118             continue;
00119 
00120         MPI_CHK( mpi_mul_mpi( &ctx->N , &ctx->P , &ctx->Q  ) );
00121         if( mpi_msb( &ctx->N  ) != nbits )
00122             continue;
00123 
00124         MPI_CHK( mpi_sub_int( &P1, &ctx->P , 1 ) );
00125         MPI_CHK( mpi_sub_int( &Q1, &ctx->Q , 1 ) );
00126         MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );
00127         MPI_CHK( mpi_gcd( &G, &ctx->E , &H  ) );
00128     }
00129     while( mpi_cmp_int( &G, 1 ) != 0 );
00130 
00131     /*
00132      * D  = E^-1 mod ((P-1)*(Q-1))
00133      * DP = D mod (P - 1)
00134      * DQ = D mod (Q - 1)
00135      * QP = Q^-1 mod P
00136      */
00137     MPI_CHK( mpi_inv_mod( &ctx->D  , &ctx->E , &H  ) );
00138     MPI_CHK( mpi_mod_mpi( &ctx->DP , &ctx->D , &P1 ) );
00139     MPI_CHK( mpi_mod_mpi( &ctx->DQ , &ctx->D , &Q1 ) );
00140     MPI_CHK( mpi_inv_mod( &ctx->QP , &ctx->Q , &ctx->P  ) );
00141 
00142     ctx->len  = ( mpi_msb( &ctx->N  ) + 7 ) >> 3;
00143 
00144 cleanup:
00145 
00146     mpi_free( &P1 ); mpi_free( &Q1 ); mpi_free( &H ); mpi_free( &G );
00147 
00148     if( ret != 0 )
00149     {
00150         rsa_free( ctx );
00151         return( POLARSSL_ERR_RSA_KEY_GEN_FAILED + ret );
00152     }
00153 
00154     return( 0 );
00155 }
00156 
00157 #endif /* POLARSSL_GENPRIME */
00158 
00159 /*
00160  * Check a public RSA key
00161  */
00162 int rsa_check_pubkey( const rsa_context *ctx )
00163 {
00164     if( !ctx->N .p  || !ctx->E .p  )
00165         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00166 
00167     if( ( ctx->N .p [0] & 1 ) == 0 ||
00168         ( ctx->E .p [0] & 1 ) == 0 )
00169         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00170 
00171     if( mpi_msb( &ctx->N  ) < 128 ||
00172         mpi_msb( &ctx->N  ) > POLARSSL_MPI_MAX_BITS )
00173         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00174 
00175     if( mpi_msb( &ctx->E  ) < 2 ||
00176         mpi_cmp_mpi( &ctx->E , &ctx->N  ) >= 0 )
00177         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00178 
00179     return( 0 );
00180 }
00181 
00182 /*
00183  * Check a private RSA key
00184  */
00185 int rsa_check_privkey( const rsa_context *ctx )
00186 {
00187     int ret;
00188     mpi PQ, DE, P1, Q1, H, I, G, G2, L1, L2, DP, DQ, QP;
00189 
00190     if( ( ret = rsa_check_pubkey( ctx ) ) != 0 )
00191         return( ret );
00192 
00193     if( !ctx->P .p  || !ctx->Q .p  || !ctx->D .p  )
00194         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00195 
00196     mpi_init( &PQ ); mpi_init( &DE ); mpi_init( &P1 ); mpi_init( &Q1 );
00197     mpi_init( &H  ); mpi_init( &I  ); mpi_init( &G  ); mpi_init( &G2 );
00198     mpi_init( &L1 ); mpi_init( &L2 ); mpi_init( &DP ); mpi_init( &DQ );
00199     mpi_init( &QP );
00200 
00201     MPI_CHK( mpi_mul_mpi( &PQ, &ctx->P , &ctx->Q  ) );
00202     MPI_CHK( mpi_mul_mpi( &DE, &ctx->D , &ctx->E  ) );
00203     MPI_CHK( mpi_sub_int( &P1, &ctx->P , 1 ) );
00204     MPI_CHK( mpi_sub_int( &Q1, &ctx->Q , 1 ) );
00205     MPI_CHK( mpi_mul_mpi( &H, &P1, &Q1 ) );
00206     MPI_CHK( mpi_gcd( &G, &ctx->E , &H  ) );
00207 
00208     MPI_CHK( mpi_gcd( &G2, &P1, &Q1 ) );
00209     MPI_CHK( mpi_div_mpi( &L1, &L2, &H, &G2 ) );
00210     MPI_CHK( mpi_mod_mpi( &I, &DE, &L1  ) );
00211 
00212     MPI_CHK( mpi_mod_mpi( &DP, &ctx->D , &P1 ) );
00213     MPI_CHK( mpi_mod_mpi( &DQ, &ctx->D , &Q1 ) );
00214     MPI_CHK( mpi_inv_mod( &QP, &ctx->Q , &ctx->P  ) );
00215     /*
00216      * Check for a valid PKCS1v2 private key
00217      */
00218     if( mpi_cmp_mpi( &PQ, &ctx->N  ) != 0 ||
00219         mpi_cmp_mpi( &DP, &ctx->DP  ) != 0 ||
00220         mpi_cmp_mpi( &DQ, &ctx->DQ  ) != 0 ||
00221         mpi_cmp_mpi( &QP, &ctx->QP  ) != 0 ||
00222         mpi_cmp_int( &L2, 0 ) != 0 ||
00223         mpi_cmp_int( &I, 1 ) != 0 ||
00224         mpi_cmp_int( &G, 1 ) != 0 )
00225     {
00226         ret = POLARSSL_ERR_RSA_KEY_CHECK_FAILED;
00227     }
00228 
00229 cleanup:
00230     mpi_free( &PQ ); mpi_free( &DE ); mpi_free( &P1 ); mpi_free( &Q1 );
00231     mpi_free( &H  ); mpi_free( &I  ); mpi_free( &G  ); mpi_free( &G2 );
00232     mpi_free( &L1 ); mpi_free( &L2 ); mpi_free( &DP ); mpi_free( &DQ );
00233     mpi_free( &QP );
00234 
00235     if( ret == POLARSSL_ERR_RSA_KEY_CHECK_FAILED )
00236         return( ret );
00237 
00238     if( ret != 0 )
00239         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED + ret );
00240 
00241     return( 0 );
00242 }
00243 
00244 /*
00245  * Check if contexts holding a public and private key match
00246  */
00247 int rsa_check_pub_priv( const rsa_context *pub, const rsa_context *prv )
00248 {
00249     if( rsa_check_pubkey( pub ) != 0 ||
00250         rsa_check_privkey( prv ) != 0 )
00251     {
00252         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00253     }
00254 
00255     if( mpi_cmp_mpi( &pub->N , &prv->N  ) != 0 ||
00256         mpi_cmp_mpi( &pub->E , &prv->E  ) != 0 )
00257     {
00258         return( POLARSSL_ERR_RSA_KEY_CHECK_FAILED );
00259     }
00260 
00261     return( 0 );
00262 }
00263 
00264 /*
00265  * Do an RSA public key operation
00266  */
00267 int rsa_public( rsa_context *ctx,
00268                 const unsigned char *input,
00269                 unsigned char *output )
00270 {
00271     int ret;
00272     size_t olen;
00273     mpi T;
00274 
00275     mpi_init( &T );
00276 
00277     MPI_CHK( mpi_read_binary( &T, input, ctx->len  ) );
00278 
00279     if( mpi_cmp_mpi( &T, &ctx->N  ) >= 0 )
00280     {
00281         mpi_free( &T );
00282         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00283     }
00284 
00285 #if defined(POLARSSL_THREADING_C)
00286     polarssl_mutex_lock( &ctx->mutex  );
00287 #endif
00288 
00289     olen = ctx->len ;
00290     MPI_CHK( mpi_exp_mod( &T, &T, &ctx->E , &ctx->N , &ctx->RN  ) );
00291     MPI_CHK( mpi_write_binary( &T, output, olen ) );
00292 
00293 cleanup:
00294 #if defined(POLARSSL_THREADING_C)
00295     polarssl_mutex_unlock( &ctx->mutex  );
00296 #endif
00297 
00298     mpi_free( &T );
00299 
00300     if( ret != 0 )
00301         return( POLARSSL_ERR_RSA_PUBLIC_FAILED + ret );
00302 
00303     return( 0 );
00304 }
00305 
00306 /*
00307  * Generate or update blinding values, see section 10 of:
00308  *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
00309  *  DSS, and other systems. In : Advances in Cryptology—CRYPTO’96. Springer
00310  *  Berlin Heidelberg, 1996. p. 104-113.
00311  */
00312 static int rsa_prepare_blinding( rsa_context *ctx, mpi *Vi, mpi *Vf,
00313                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
00314 {
00315     int ret, count = 0;
00316 
00317 #if defined(POLARSSL_THREADING_C)
00318     polarssl_mutex_lock( &ctx->mutex  );
00319 #endif
00320 
00321     if( ctx->Vf .p  != NULL )
00322     {
00323         /* We already have blinding values, just update them by squaring */
00324         MPI_CHK( mpi_mul_mpi( &ctx->Vi , &ctx->Vi , &ctx->Vi  ) );
00325         MPI_CHK( mpi_mod_mpi( &ctx->Vi , &ctx->Vi , &ctx->N  ) );
00326         MPI_CHK( mpi_mul_mpi( &ctx->Vf , &ctx->Vf , &ctx->Vf  ) );
00327         MPI_CHK( mpi_mod_mpi( &ctx->Vf , &ctx->Vf , &ctx->N  ) );
00328 
00329         goto done;
00330     }
00331 
00332     /* Unblinding value: Vf = random number, invertible mod N */
00333     do {
00334         if( count++ > 10 )
00335             return( POLARSSL_ERR_RSA_RNG_FAILED );
00336 
00337         MPI_CHK( mpi_fill_random( &ctx->Vf , ctx->len  - 1, f_rng, p_rng ) );
00338         MPI_CHK( mpi_gcd( &ctx->Vi , &ctx->Vf , &ctx->N  ) );
00339     } while( mpi_cmp_int( &ctx->Vi , 1 ) != 0 );
00340 
00341     /* Blinding value: Vi =  Vf^(-e) mod N */
00342     MPI_CHK( mpi_inv_mod( &ctx->Vi , &ctx->Vf , &ctx->N  ) );
00343     MPI_CHK( mpi_exp_mod( &ctx->Vi , &ctx->Vi , &ctx->E , &ctx->N , &ctx->RN  ) );
00344 
00345 done:
00346     if( Vi != &ctx->Vi  )
00347     {
00348         MPI_CHK( mpi_copy( Vi, &ctx->Vi  ) );
00349         MPI_CHK( mpi_copy( Vf, &ctx->Vf  ) );
00350     }
00351 
00352 cleanup:
00353 #if defined(POLARSSL_THREADING_C)
00354     polarssl_mutex_unlock( &ctx->mutex  );
00355 #endif
00356 
00357     return( ret );
00358 }
00359 
00360 /*
00361  * Do an RSA private key operation
00362  */
00363 int rsa_private( rsa_context *ctx,
00364                  int (*f_rng)(void *, unsigned char *, size_t),
00365                  void *p_rng,
00366                  const unsigned char *input,
00367                  unsigned char *output )
00368 {
00369     int ret;
00370     size_t olen;
00371     mpi T, T1, T2;
00372     mpi *Vi, *Vf;
00373 
00374     /*
00375      * When using the Chinese Remainder Theorem, we use blinding values.
00376      * Without threading, we just read them directly from the context,
00377      * otherwise we make a local copy in order to reduce locking contention.
00378      */
00379 #if defined(POLARSSL_THREADING_C)
00380     mpi Vi_copy, Vf_copy;
00381 
00382     mpi_init( &Vi_copy ); mpi_init( &Vf_copy );
00383     Vi = &Vi_copy;
00384     Vf = &Vf_copy;
00385 #else
00386     Vi = &ctx->Vi ;
00387     Vf = &ctx->Vf ;
00388 #endif
00389 
00390     mpi_init( &T ); mpi_init( &T1 ); mpi_init( &T2 );
00391 
00392     MPI_CHK( mpi_read_binary( &T, input, ctx->len  ) );
00393     if( mpi_cmp_mpi( &T, &ctx->N  ) >= 0 )
00394     {
00395         mpi_free( &T );
00396         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00397     }
00398 
00399     if( f_rng != NULL )
00400     {
00401         /*
00402          * Blinding
00403          * T = T * Vi mod N
00404          */
00405         MPI_CHK( rsa_prepare_blinding( ctx, Vi, Vf, f_rng, p_rng ) );
00406         MPI_CHK( mpi_mul_mpi( &T, &T, Vi ) );
00407         MPI_CHK( mpi_mod_mpi( &T, &T, &ctx->N  ) );
00408     }
00409 
00410 #if defined(POLARSSL_THREADING_C)
00411     polarssl_mutex_lock( &ctx->mutex  );
00412 #endif
00413 
00414 #if defined(POLARSSL_RSA_NO_CRT)
00415     MPI_CHK( mpi_exp_mod( &T, &T, &ctx->D , &ctx->N , &ctx->RN  ) );
00416 #else
00417     /*
00418      * faster decryption using the CRT
00419      *
00420      * T1 = input ^ dP mod P
00421      * T2 = input ^ dQ mod Q
00422      */
00423     MPI_CHK( mpi_exp_mod( &T1, &T, &ctx->DP , &ctx->P , &ctx->RP  ) );
00424     MPI_CHK( mpi_exp_mod( &T2, &T, &ctx->DQ , &ctx->Q , &ctx->RQ  ) );
00425 
00426     /*
00427      * T = (T1 - T2) * (Q^-1 mod P) mod P
00428      */
00429     MPI_CHK( mpi_sub_mpi( &T, &T1, &T2 ) );
00430     MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->QP  ) );
00431     MPI_CHK( mpi_mod_mpi( &T, &T1, &ctx->P  ) );
00432 
00433     /*
00434      * T = T2 + T * Q
00435      */
00436     MPI_CHK( mpi_mul_mpi( &T1, &T, &ctx->Q  ) );
00437     MPI_CHK( mpi_add_mpi( &T, &T2, &T1 ) );
00438 #endif /* POLARSSL_RSA_NO_CRT */
00439 
00440     if( f_rng != NULL )
00441     {
00442         /*
00443          * Unblind
00444          * T = T * Vf mod N
00445          */
00446         MPI_CHK( mpi_mul_mpi( &T, &T, Vf ) );
00447         MPI_CHK( mpi_mod_mpi( &T, &T, &ctx->N  ) );
00448     }
00449 
00450     olen = ctx->len ;
00451     MPI_CHK( mpi_write_binary( &T, output, olen ) );
00452 
00453 cleanup:
00454 #if defined(POLARSSL_THREADING_C)
00455     polarssl_mutex_unlock( &ctx->mutex  );
00456     mpi_free( &Vi_copy ); mpi_free( &Vf_copy );
00457 #endif
00458     mpi_free( &T ); mpi_free( &T1 ); mpi_free( &T2 );
00459 
00460     if( ret != 0 )
00461         return( POLARSSL_ERR_RSA_PRIVATE_FAILED + ret );
00462 
00463     return( 0 );
00464 }
00465 
00466 #if defined(POLARSSL_PKCS1_V21)
00467 /**
00468  * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
00469  *
00470  * \param dst       buffer to mask
00471  * \param dlen      length of destination buffer
00472  * \param src       source of the mask generation
00473  * \param slen      length of the source buffer
00474  * \param md_ctx    message digest context to use
00475  */
00476 static void mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
00477                       size_t slen, md_context_t *md_ctx )
00478 {
00479     unsigned char mask[POLARSSL_MD_MAX_SIZE];
00480     unsigned char counter[4];
00481     unsigned char *p;
00482     unsigned int hlen;
00483     size_t i, use_len;
00484 
00485     memset( mask, 0, POLARSSL_MD_MAX_SIZE );
00486     memset( counter, 0, 4 );
00487 
00488     hlen = md_ctx->md_info->size;
00489 
00490     // Generate and apply dbMask
00491     //
00492     p = dst;
00493 
00494     while( dlen > 0 )
00495     {
00496         use_len = hlen;
00497         if( dlen < hlen )
00498             use_len = dlen;
00499 
00500         md_starts( md_ctx );
00501         md_update( md_ctx, src, slen );
00502         md_update( md_ctx, counter, 4 );
00503         md_finish( md_ctx, mask );
00504 
00505         for( i = 0; i < use_len; ++i )
00506             *p++ ^= mask[i];
00507 
00508         counter[3]++;
00509 
00510         dlen -= use_len;
00511     }
00512 }
00513 #endif /* POLARSSL_PKCS1_V21 */
00514 
00515 #if defined(POLARSSL_PKCS1_V21)
00516 /*
00517  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
00518  */
00519 int rsa_rsaes_oaep_encrypt( rsa_context *ctx,
00520                             int (*f_rng)(void *, unsigned char *, size_t),
00521                             void *p_rng,
00522                             int mode,
00523                             const unsigned char *label, size_t label_len,
00524                             size_t ilen,
00525                             const unsigned char *input,
00526                             unsigned char *output )
00527 {
00528     size_t olen;
00529     int ret;
00530     unsigned char *p = output;
00531     unsigned int hlen;
00532     const md_info_t *md_info;
00533     md_context_t md_ctx;
00534 
00535     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V21 )
00536         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00537 
00538     if( f_rng == NULL )
00539         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00540 
00541     md_info = md_info_from_type( (md_type_t) ctx->hash_id  );
00542     if( md_info == NULL )
00543         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00544 
00545     olen = ctx->len ;
00546     hlen = md_get_size( md_info );
00547 
00548     if( olen < ilen + 2 * hlen + 2 )
00549         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00550 
00551     memset( output, 0, olen );
00552 
00553     *p++ = 0;
00554 
00555     // Generate a random octet string seed
00556     //
00557     if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
00558         return( POLARSSL_ERR_RSA_RNG_FAILED + ret );
00559 
00560     p += hlen;
00561 
00562     // Construct DB
00563     //
00564     md( md_info, label, label_len, p );
00565     p += hlen;
00566     p += olen - 2 * hlen - 2 - ilen;
00567     *p++ = 1;
00568     memcpy( p, input, ilen );
00569 
00570     md_init( &md_ctx );
00571     md_init_ctx( &md_ctx, md_info );
00572 
00573     // maskedDB: Apply dbMask to DB
00574     //
00575     mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
00576                &md_ctx );
00577 
00578     // maskedSeed: Apply seedMask to seed
00579     //
00580     mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
00581                &md_ctx );
00582 
00583     md_free( &md_ctx );
00584 
00585     return( ( mode == RSA_PUBLIC )
00586             ? rsa_public(  ctx, output, output )
00587             : rsa_private( ctx, f_rng, p_rng, output, output ) );
00588 }
00589 #endif /* POLARSSL_PKCS1_V21 */
00590 
00591 #if defined(POLARSSL_PKCS1_V15)
00592 /*
00593  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
00594  */
00595 int rsa_rsaes_pkcs1_v15_encrypt( rsa_context *ctx,
00596                                  int (*f_rng)(void *, unsigned char *, size_t),
00597                                  void *p_rng,
00598                                  int mode, size_t ilen,
00599                                  const unsigned char *input,
00600                                  unsigned char *output )
00601 {
00602     size_t nb_pad, olen;
00603     int ret;
00604     unsigned char *p = output;
00605 
00606     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V15 )
00607         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00608 
00609     if( f_rng == NULL )
00610         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00611 
00612     olen = ctx->len ;
00613 
00614     if( olen < ilen + 11 )
00615         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00616 
00617     nb_pad = olen - 3 - ilen;
00618 
00619     *p++ = 0;
00620     if( mode == RSA_PUBLIC )
00621     {
00622         *p++ = RSA_CRYPT;
00623 
00624         while( nb_pad-- > 0 )
00625         {
00626             int rng_dl = 100;
00627 
00628             do {
00629                 ret = f_rng( p_rng, p, 1 );
00630             } while( *p == 0 && --rng_dl && ret == 0 );
00631 
00632             // Check if RNG failed to generate data
00633             //
00634             if( rng_dl == 0 || ret != 0 )
00635                 return( POLARSSL_ERR_RSA_RNG_FAILED + ret );
00636 
00637             p++;
00638         }
00639     }
00640     else
00641     {
00642         *p++ = RSA_SIGN;
00643 
00644         while( nb_pad-- > 0 )
00645             *p++ = 0xFF;
00646     }
00647 
00648     *p++ = 0;
00649     memcpy( p, input, ilen );
00650 
00651     return( ( mode == RSA_PUBLIC )
00652             ? rsa_public(  ctx, output, output )
00653             : rsa_private( ctx, f_rng, p_rng, output, output ) );
00654 }
00655 #endif /* POLARSSL_PKCS1_V15 */
00656 
00657 /*
00658  * Add the message padding, then do an RSA operation
00659  */
00660 int rsa_pkcs1_encrypt( rsa_context *ctx,
00661                        int (*f_rng)(void *, unsigned char *, size_t),
00662                        void *p_rng,
00663                        int mode, size_t ilen,
00664                        const unsigned char *input,
00665                        unsigned char *output )
00666 {
00667     switch( ctx->padding  )
00668     {
00669 #if defined(POLARSSL_PKCS1_V15)
00670         case RSA_PKCS_V15:
00671             return rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,
00672                                                 input, output );
00673 #endif
00674 
00675 #if defined(POLARSSL_PKCS1_V21)
00676         case RSA_PKCS_V21:
00677             return rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,
00678                                            ilen, input, output );
00679 #endif
00680 
00681         default:
00682             return( POLARSSL_ERR_RSA_INVALID_PADDING );
00683     }
00684 }
00685 
00686 #if defined(POLARSSL_PKCS1_V21)
00687 /*
00688  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
00689  */
00690 int rsa_rsaes_oaep_decrypt( rsa_context *ctx,
00691                             int (*f_rng)(void *, unsigned char *, size_t),
00692                             void *p_rng,
00693                             int mode,
00694                             const unsigned char *label, size_t label_len,
00695                             size_t *olen,
00696                             const unsigned char *input,
00697                             unsigned char *output,
00698                             size_t output_max_len )
00699 {
00700     int ret;
00701     size_t ilen, i, pad_len;
00702     unsigned char *p, bad, pad_done;
00703     unsigned char buf[POLARSSL_MPI_MAX_SIZE];
00704     unsigned char lhash[POLARSSL_MD_MAX_SIZE];
00705     unsigned int hlen;
00706     const md_info_t *md_info;
00707     md_context_t md_ctx;
00708 
00709     /*
00710      * Parameters sanity checks
00711      */
00712     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V21 )
00713         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00714 
00715     ilen = ctx->len ;
00716 
00717     if( ilen < 16 || ilen > sizeof( buf ) )
00718         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00719 
00720     md_info = md_info_from_type( (md_type_t) ctx->hash_id  );
00721     if( md_info == NULL )
00722         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00723 
00724     /*
00725      * RSA operation
00726      */
00727     ret = ( mode == RSA_PUBLIC )
00728           ? rsa_public(  ctx, input, buf )
00729           : rsa_private( ctx, f_rng, p_rng, input, buf );
00730 
00731     if( ret != 0 )
00732         return( ret );
00733 
00734     /*
00735      * Unmask data and generate lHash
00736      */
00737     hlen = md_get_size( md_info );
00738 
00739     md_init( &md_ctx );
00740     md_init_ctx( &md_ctx, md_info );
00741 
00742     /* Generate lHash */
00743     md( md_info, label, label_len, lhash );
00744 
00745     /* seed: Apply seedMask to maskedSeed */
00746     mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
00747                &md_ctx );
00748 
00749     /* DB: Apply dbMask to maskedDB */
00750     mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
00751                &md_ctx );
00752 
00753     md_free( &md_ctx );
00754 
00755     /*
00756      * Check contents, in "constant-time"
00757      */
00758     p = buf;
00759     bad = 0;
00760 
00761     bad |= *p++; /* First byte must be 0 */
00762 
00763     p += hlen; /* Skip seed */
00764 
00765     /* Check lHash */
00766     for( i = 0; i < hlen; i++ )
00767         bad |= lhash[i] ^ *p++;
00768 
00769     /* Get zero-padding len, but always read till end of buffer
00770      * (minus one, for the 01 byte) */
00771     pad_len = 0;
00772     pad_done = 0;
00773     for( i = 0; i < ilen - 2 * hlen - 2; i++ )
00774     {
00775         pad_done |= p[i];
00776         pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
00777     }
00778 
00779     p += pad_len;
00780     bad |= *p++ ^ 0x01;
00781 
00782     /*
00783      * The only information "leaked" is whether the padding was correct or not
00784      * (eg, no data is copied if it was not correct). This meets the
00785      * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
00786      * the different error conditions.
00787      */
00788     if( bad != 0 )
00789         return( POLARSSL_ERR_RSA_INVALID_PADDING );
00790 
00791     if( ilen - ( p - buf ) > output_max_len )
00792         return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );
00793 
00794     *olen = ilen - (p - buf);
00795     memcpy( output, p, *olen );
00796 
00797     return( 0 );
00798 }
00799 #endif /* POLARSSL_PKCS1_V21 */
00800 
00801 #if defined(POLARSSL_PKCS1_V15)
00802 /*
00803  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
00804  */
00805 int rsa_rsaes_pkcs1_v15_decrypt( rsa_context *ctx,
00806                                  int (*f_rng)(void *, unsigned char *, size_t),
00807                                  void *p_rng,
00808                                  int mode, size_t *olen,
00809                                  const unsigned char *input,
00810                                  unsigned char *output,
00811                                  size_t output_max_len)
00812 {
00813     int ret;
00814     size_t ilen, pad_count = 0, i;
00815     unsigned char *p, bad, pad_done = 0;
00816     unsigned char buf[POLARSSL_MPI_MAX_SIZE];
00817 
00818     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V15 )
00819         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00820 
00821     ilen = ctx->len ;
00822 
00823     if( ilen < 16 || ilen > sizeof( buf ) )
00824         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00825 
00826     ret = ( mode == RSA_PUBLIC )
00827           ? rsa_public(  ctx, input, buf )
00828           : rsa_private( ctx, f_rng, p_rng, input, buf );
00829 
00830     if( ret != 0 )
00831         return( ret );
00832 
00833     p = buf;
00834     bad = 0;
00835 
00836     /*
00837      * Check and get padding len in "constant-time"
00838      */
00839     bad |= *p++; /* First byte must be 0 */
00840 
00841     /* This test does not depend on secret data */
00842     if( mode == RSA_PRIVATE )
00843     {
00844         bad |= *p++ ^ RSA_CRYPT;
00845 
00846         /* Get padding len, but always read till end of buffer
00847          * (minus one, for the 00 byte) */
00848         for( i = 0; i < ilen - 3; i++ )
00849         {
00850             pad_done  |= ((p[i] | (unsigned char)-p[i]) >> 7) ^ 1;
00851             pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
00852         }
00853 
00854         p += pad_count;
00855         bad |= *p++; /* Must be zero */
00856     }
00857     else
00858     {
00859         bad |= *p++ ^ RSA_SIGN;
00860 
00861         /* Get padding len, but always read till end of buffer
00862          * (minus one, for the 00 byte) */
00863         for( i = 0; i < ilen - 3; i++ )
00864         {
00865             pad_done |= ( p[i] != 0xFF );
00866             pad_count += ( pad_done == 0 );
00867         }
00868 
00869         p += pad_count;
00870         bad |= *p++; /* Must be zero */
00871     }
00872 
00873     if( bad )
00874         return( POLARSSL_ERR_RSA_INVALID_PADDING );
00875 
00876     if( ilen - ( p - buf ) > output_max_len )
00877         return( POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE );
00878 
00879     *olen = ilen - (p - buf);
00880     memcpy( output, p, *olen );
00881 
00882     return( 0 );
00883 }
00884 #endif /* POLARSSL_PKCS1_V15 */
00885 
00886 /*
00887  * Do an RSA operation, then remove the message padding
00888  */
00889 int rsa_pkcs1_decrypt( rsa_context *ctx,
00890                        int (*f_rng)(void *, unsigned char *, size_t),
00891                        void *p_rng,
00892                        int mode, size_t *olen,
00893                        const unsigned char *input,
00894                        unsigned char *output,
00895                        size_t output_max_len)
00896 {
00897     switch( ctx->padding  )
00898     {
00899 #if defined(POLARSSL_PKCS1_V15)
00900         case RSA_PKCS_V15:
00901             return rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,
00902                                                 input, output, output_max_len );
00903 #endif
00904 
00905 #if defined(POLARSSL_PKCS1_V21)
00906         case RSA_PKCS_V21:
00907             return rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,
00908                                            olen, input, output,
00909                                            output_max_len );
00910 #endif
00911 
00912         default:
00913             return( POLARSSL_ERR_RSA_INVALID_PADDING );
00914     }
00915 }
00916 
00917 #if defined(POLARSSL_PKCS1_V21)
00918 /*
00919  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
00920  */
00921 int rsa_rsassa_pss_sign( rsa_context *ctx,
00922                          int (*f_rng)(void *, unsigned char *, size_t),
00923                          void *p_rng,
00924                          int mode,
00925                          md_type_t md_alg,
00926                          unsigned int hashlen,
00927                          const unsigned char *hash,
00928                          unsigned char *sig )
00929 {
00930     size_t olen;
00931     unsigned char *p = sig;
00932     unsigned char salt[POLARSSL_MD_MAX_SIZE];
00933     unsigned int slen, hlen, offset = 0;
00934     int ret;
00935     size_t msb;
00936     const md_info_t *md_info;
00937     md_context_t md_ctx;
00938 
00939     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V21 )
00940         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00941 
00942     if( f_rng == NULL )
00943         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00944 
00945     olen = ctx->len ;
00946 
00947     if( md_alg != POLARSSL_MD_NONE )
00948     {
00949         // Gather length of hash to sign
00950         //
00951         md_info = md_info_from_type( md_alg );
00952         if( md_info == NULL )
00953             return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00954 
00955         hashlen = md_get_size( md_info );
00956     }
00957 
00958     md_info = md_info_from_type( (md_type_t) ctx->hash_id  );
00959     if( md_info == NULL )
00960         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00961 
00962     hlen = md_get_size( md_info );
00963     slen = hlen;
00964 
00965     if( olen < hlen + slen + 2 )
00966         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
00967 
00968     memset( sig, 0, olen );
00969 
00970     // Generate salt of length slen
00971     //
00972     if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
00973         return( POLARSSL_ERR_RSA_RNG_FAILED + ret );
00974 
00975     // Note: EMSA-PSS encoding is over the length of N - 1 bits
00976     //
00977     msb = mpi_msb( &ctx->N  ) - 1;
00978     p += olen - hlen * 2 - 2;
00979     *p++ = 0x01;
00980     memcpy( p, salt, slen );
00981     p += slen;
00982 
00983     md_init( &md_ctx );
00984     md_init_ctx( &md_ctx, md_info );
00985 
00986     // Generate H = Hash( M' )
00987     //
00988     md_starts( &md_ctx );
00989     md_update( &md_ctx, p, 8 );
00990     md_update( &md_ctx, hash, hashlen );
00991     md_update( &md_ctx, salt, slen );
00992     md_finish( &md_ctx, p );
00993 
00994     // Compensate for boundary condition when applying mask
00995     //
00996     if( msb % 8 == 0 )
00997         offset = 1;
00998 
00999     // maskedDB: Apply dbMask to DB
01000     //
01001     mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen, &md_ctx );
01002 
01003     md_free( &md_ctx );
01004 
01005     msb = mpi_msb( &ctx->N  ) - 1;
01006     sig[0] &= 0xFF >> ( olen * 8 - msb );
01007 
01008     p += hlen;
01009     *p++ = 0xBC;
01010 
01011     return( ( mode == RSA_PUBLIC )
01012             ? rsa_public(  ctx, sig, sig )
01013             : rsa_private( ctx, f_rng, p_rng, sig, sig ) );
01014 }
01015 #endif /* POLARSSL_PKCS1_V21 */
01016 
01017 #if defined(POLARSSL_PKCS1_V15)
01018 /*
01019  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
01020  */
01021 /*
01022  * Do an RSA operation to sign the message digest
01023  */
01024 int rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx,
01025                                int (*f_rng)(void *, unsigned char *, size_t),
01026                                void *p_rng,
01027                                int mode,
01028                                md_type_t md_alg,
01029                                unsigned int hashlen,
01030                                const unsigned char *hash,
01031                                unsigned char *sig )
01032 {
01033     size_t nb_pad, olen, oid_size = 0;
01034     unsigned char *p = sig;
01035     const char *oid = NULL;
01036 
01037     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V15 )
01038         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01039 
01040     olen = ctx->len ;
01041     nb_pad = olen - 3;
01042 
01043     if( md_alg != POLARSSL_MD_NONE )
01044     {
01045         const md_info_t *md_info = md_info_from_type( md_alg );
01046         if( md_info == NULL )
01047             return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01048 
01049         if( oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
01050             return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01051 
01052         nb_pad -= 10 + oid_size;
01053 
01054         hashlen = md_get_size( md_info );
01055     }
01056 
01057     nb_pad -= hashlen;
01058 
01059     if( ( nb_pad < 8 ) || ( nb_pad > olen ) )
01060         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01061 
01062     *p++ = 0;
01063     *p++ = RSA_SIGN;
01064     memset( p, 0xFF, nb_pad );
01065     p += nb_pad;
01066     *p++ = 0;
01067 
01068     if( md_alg == POLARSSL_MD_NONE )
01069     {
01070         memcpy( p, hash, hashlen );
01071     }
01072     else
01073     {
01074         /*
01075          * DigestInfo ::= SEQUENCE {
01076          *   digestAlgorithm DigestAlgorithmIdentifier,
01077          *   digest Digest }
01078          *
01079          * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
01080          *
01081          * Digest ::= OCTET STRING
01082          */
01083         *p++ = ASN1_SEQUENCE | ASN1_CONSTRUCTED;
01084         *p++ = (unsigned char) ( 0x08 + oid_size + hashlen );
01085         *p++ = ASN1_SEQUENCE | ASN1_CONSTRUCTED;
01086         *p++ = (unsigned char) ( 0x04 + oid_size );
01087         *p++ = ASN1_OID;
01088         *p++ = oid_size & 0xFF;
01089         memcpy( p, oid, oid_size );
01090         p += oid_size;
01091         *p++ = ASN1_NULL;
01092         *p++ = 0x00;
01093         *p++ = ASN1_OCTET_STRING;
01094         *p++ = hashlen;
01095         memcpy( p, hash, hashlen );
01096     }
01097 
01098     return( ( mode == RSA_PUBLIC )
01099             ? rsa_public(  ctx, sig, sig )
01100             : rsa_private( ctx, f_rng, p_rng, sig, sig ) );
01101 }
01102 #endif /* POLARSSL_PKCS1_V15 */
01103 
01104 /*
01105  * Do an RSA operation to sign the message digest
01106  */
01107 int rsa_pkcs1_sign( rsa_context *ctx,
01108                     int (*f_rng)(void *, unsigned char *, size_t),
01109                     void *p_rng,
01110                     int mode,
01111                     md_type_t md_alg,
01112                     unsigned int hashlen,
01113                     const unsigned char *hash,
01114                     unsigned char *sig )
01115 {
01116     switch( ctx->padding  )
01117     {
01118 #if defined(POLARSSL_PKCS1_V15)
01119         case RSA_PKCS_V15:
01120             return rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,
01121                                               hashlen, hash, sig );
01122 #endif
01123 
01124 #if defined(POLARSSL_PKCS1_V21)
01125         case RSA_PKCS_V21:
01126             return rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
01127                                         hashlen, hash, sig );
01128 #endif
01129 
01130         default:
01131             return( POLARSSL_ERR_RSA_INVALID_PADDING );
01132     }
01133 }
01134 
01135 #if defined(POLARSSL_PKCS1_V21)
01136 /*
01137  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
01138  */
01139 int rsa_rsassa_pss_verify_ext( rsa_context *ctx,
01140                                int (*f_rng)(void *, unsigned char *, size_t),
01141                                void *p_rng,
01142                                int mode,
01143                                md_type_t md_alg,
01144                                unsigned int hashlen,
01145                                const unsigned char *hash,
01146                                md_type_t mgf1_hash_id,
01147                                int expected_salt_len,
01148                                const unsigned char *sig )
01149 {
01150     int ret;
01151     size_t siglen;
01152     unsigned char *p;
01153     unsigned char buf[POLARSSL_MPI_MAX_SIZE];
01154     unsigned char result[POLARSSL_MD_MAX_SIZE];
01155     unsigned char zeros[8];
01156     unsigned int hlen;
01157     size_t slen, msb;
01158     const md_info_t *md_info;
01159     md_context_t md_ctx;
01160 
01161     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V21 )
01162         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01163 
01164     siglen = ctx->len ;
01165 
01166     if( siglen < 16 || siglen > sizeof( buf ) )
01167         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01168 
01169     ret = ( mode == RSA_PUBLIC )
01170           ? rsa_public(  ctx, sig, buf )
01171           : rsa_private( ctx, f_rng, p_rng, sig, buf );
01172 
01173     if( ret != 0 )
01174         return( ret );
01175 
01176     p = buf;
01177 
01178     if( buf[siglen - 1] != 0xBC )
01179         return( POLARSSL_ERR_RSA_INVALID_PADDING );
01180 
01181     if( md_alg != POLARSSL_MD_NONE )
01182     {
01183         // Gather length of hash to sign
01184         //
01185         md_info = md_info_from_type( md_alg );
01186         if( md_info == NULL )
01187             return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01188 
01189         hashlen = md_get_size( md_info );
01190     }
01191 
01192     md_info = md_info_from_type( mgf1_hash_id );
01193     if( md_info == NULL )
01194         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01195 
01196     hlen = md_get_size( md_info );
01197     slen = siglen - hlen - 1; /* Currently length of salt + padding */
01198 
01199     memset( zeros, 0, 8 );
01200 
01201     // Note: EMSA-PSS verification is over the length of N - 1 bits
01202     //
01203     msb = mpi_msb( &ctx->N  ) - 1;
01204 
01205     // Compensate for boundary condition when applying mask
01206     //
01207     if( msb % 8 == 0 )
01208     {
01209         p++;
01210         siglen -= 1;
01211     }
01212     if( buf[0] >> ( 8 - siglen * 8 + msb ) )
01213         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01214 
01215     md_init( &md_ctx );
01216     md_init_ctx( &md_ctx, md_info );
01217 
01218     mgf_mask( p, siglen - hlen - 1, p + siglen - hlen - 1, hlen, &md_ctx );
01219 
01220     buf[0] &= 0xFF >> ( siglen * 8 - msb );
01221 
01222     while( p < buf + siglen && *p == 0 )
01223         p++;
01224 
01225     if( p == buf + siglen ||
01226         *p++ != 0x01 )
01227     {
01228         md_free( &md_ctx );
01229         return( POLARSSL_ERR_RSA_INVALID_PADDING );
01230     }
01231 
01232     /* Actual salt len */
01233     slen -= p - buf;
01234 
01235     if( expected_salt_len != RSA_SALT_LEN_ANY &&
01236         slen != (size_t) expected_salt_len )
01237     {
01238         md_free( &md_ctx );
01239         return( POLARSSL_ERR_RSA_INVALID_PADDING );
01240     }
01241 
01242     // Generate H = Hash( M' )
01243     //
01244     md_starts( &md_ctx );
01245     md_update( &md_ctx, zeros, 8 );
01246     md_update( &md_ctx, hash, hashlen );
01247     md_update( &md_ctx, p, slen );
01248     md_finish( &md_ctx, result );
01249 
01250     md_free( &md_ctx );
01251 
01252     if( memcmp( p + slen, result, hlen ) == 0 )
01253         return( 0 );
01254     else
01255         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01256 }
01257 
01258 /*
01259  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
01260  */
01261 int rsa_rsassa_pss_verify( rsa_context *ctx,
01262                            int (*f_rng)(void *, unsigned char *, size_t),
01263                            void *p_rng,
01264                            int mode,
01265                            md_type_t md_alg,
01266                            unsigned int hashlen,
01267                            const unsigned char *hash,
01268                            const unsigned char *sig )
01269 {
01270     md_type_t mgf1_hash_id = ( ctx->hash_id  != POLARSSL_MD_NONE )
01271                              ? (md_type_t) ctx->hash_id 
01272                              : md_alg;
01273 
01274     return( rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,
01275                                        md_alg, hashlen, hash,
01276                                        mgf1_hash_id, RSA_SALT_LEN_ANY,
01277                                        sig ) );
01278 
01279 }
01280 #endif /* POLARSSL_PKCS1_V21 */
01281 
01282 #if defined(POLARSSL_PKCS1_V15)
01283 /*
01284  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
01285  */
01286 int rsa_rsassa_pkcs1_v15_verify( rsa_context *ctx,
01287                                  int (*f_rng)(void *, unsigned char *, size_t),
01288                                  void *p_rng,
01289                                  int mode,
01290                                  md_type_t md_alg,
01291                                  unsigned int hashlen,
01292                                  const unsigned char *hash,
01293                                  const unsigned char *sig )
01294 {
01295     int ret;
01296     size_t len, siglen, asn1_len;
01297     unsigned char *p, *end;
01298     unsigned char buf[POLARSSL_MPI_MAX_SIZE];
01299     md_type_t msg_md_alg;
01300     const md_info_t *md_info;
01301     asn1_buf oid;
01302 
01303     if( mode == RSA_PRIVATE && ctx->padding  != RSA_PKCS_V15 )
01304         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01305 
01306     siglen = ctx->len ;
01307 
01308     if( siglen < 16 || siglen > sizeof( buf ) )
01309         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01310 
01311     ret = ( mode == RSA_PUBLIC )
01312           ? rsa_public(  ctx, sig, buf )
01313           : rsa_private( ctx, f_rng, p_rng, sig, buf );
01314 
01315     if( ret != 0 )
01316         return( ret );
01317 
01318     p = buf;
01319 
01320     if( *p++ != 0 || *p++ != RSA_SIGN )
01321         return( POLARSSL_ERR_RSA_INVALID_PADDING );
01322 
01323     while( *p != 0 )
01324     {
01325         if( p >= buf + siglen - 1 || *p != 0xFF )
01326             return( POLARSSL_ERR_RSA_INVALID_PADDING );
01327         p++;
01328     }
01329     p++;
01330 
01331     len = siglen - ( p - buf );
01332 
01333     if( len == hashlen && md_alg == POLARSSL_MD_NONE )
01334     {
01335         if( memcmp( p, hash, hashlen ) == 0 )
01336             return( 0 );
01337         else
01338             return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01339     }
01340 
01341     md_info = md_info_from_type( md_alg );
01342     if( md_info == NULL )
01343         return( POLARSSL_ERR_RSA_BAD_INPUT_DATA );
01344     hashlen = md_get_size( md_info );
01345 
01346     end = p + len;
01347 
01348     // Parse the ASN.1 structure inside the PKCS#1 v1.5 structure
01349     //
01350     if( ( ret = asn1_get_tag( &p, end, &asn1_len,
01351             ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
01352         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01353 
01354     if( asn1_len + 2 != len )
01355         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01356 
01357     if( ( ret = asn1_get_tag( &p, end, &asn1_len,
01358             ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
01359         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01360 
01361     if( asn1_len + 6 + hashlen != len )
01362         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01363 
01364     if( ( ret = asn1_get_tag( &p, end, &oid.len, ASN1_OID ) ) != 0 )
01365         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01366 
01367     oid.p = p;
01368     p += oid.len;
01369 
01370     if( oid_get_md_alg( &oid, &msg_md_alg ) != 0 )
01371         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01372 
01373     if( md_alg != msg_md_alg )
01374         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01375 
01376     /*
01377      * assume the algorithm parameters must be NULL
01378      */
01379     if( ( ret = asn1_get_tag( &p, end, &asn1_len, ASN1_NULL ) ) != 0 )
01380         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01381 
01382     if( ( ret = asn1_get_tag( &p, end, &asn1_len, ASN1_OCTET_STRING ) ) != 0 )
01383         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01384 
01385     if( asn1_len != hashlen )
01386         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01387 
01388     if( memcmp( p, hash, hashlen ) != 0 )
01389         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01390 
01391     p += hashlen;
01392 
01393     if( p != end )
01394         return( POLARSSL_ERR_RSA_VERIFY_FAILED );
01395 
01396     return( 0 );
01397 }
01398 #endif /* POLARSSL_PKCS1_V15 */
01399 
01400 /*
01401  * Do an RSA operation and check the message digest
01402  */
01403 int rsa_pkcs1_verify( rsa_context *ctx,
01404                       int (*f_rng)(void *, unsigned char *, size_t),
01405                       void *p_rng,
01406                       int mode,
01407                       md_type_t md_alg,
01408                       unsigned int hashlen,
01409                       const unsigned char *hash,
01410                       const unsigned char *sig )
01411 {
01412     switch( ctx->padding  )
01413     {
01414 #if defined(POLARSSL_PKCS1_V15)
01415         case RSA_PKCS_V15:
01416             return rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,
01417                                                 hashlen, hash, sig );
01418 #endif
01419 
01420 #if defined(POLARSSL_PKCS1_V21)
01421         case RSA_PKCS_V21:
01422             return rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,
01423                                           hashlen, hash, sig );
01424 #endif
01425 
01426         default:
01427             return( POLARSSL_ERR_RSA_INVALID_PADDING );
01428     }
01429 }
01430 
01431 /*
01432  * Copy the components of an RSA key
01433  */
01434 int rsa_copy( rsa_context *dst, const rsa_context *src )
01435 {
01436     int ret;
01437 
01438     dst->ver  = src->ver ;
01439     dst->len  = src->len ;
01440 
01441     MPI_CHK( mpi_copy( &dst->N , &src->N  ) );
01442     MPI_CHK( mpi_copy( &dst->E , &src->E  ) );
01443 
01444     MPI_CHK( mpi_copy( &dst->D , &src->D  ) );
01445     MPI_CHK( mpi_copy( &dst->P , &src->P  ) );
01446     MPI_CHK( mpi_copy( &dst->Q , &src->Q  ) );
01447     MPI_CHK( mpi_copy( &dst->DP , &src->DP  ) );
01448     MPI_CHK( mpi_copy( &dst->DQ , &src->DQ  ) );
01449     MPI_CHK( mpi_copy( &dst->QP , &src->QP  ) );
01450 
01451     MPI_CHK( mpi_copy( &dst->RN , &src->RN  ) );
01452     MPI_CHK( mpi_copy( &dst->RP , &src->RP  ) );
01453     MPI_CHK( mpi_copy( &dst->RQ , &src->RQ  ) );
01454 
01455     MPI_CHK( mpi_copy( &dst->Vi , &src->Vi  ) );
01456     MPI_CHK( mpi_copy( &dst->Vf , &src->Vf  ) );
01457 
01458     dst->padding  = src->padding ;
01459     dst->hash_id  = src->hash_id ;
01460 
01461 cleanup:
01462     if( ret != 0 )
01463         rsa_free( dst );
01464 
01465     return( ret );
01466 }
01467 
01468 /*
01469  * Free the components of an RSA key
01470  */
01471 void rsa_free( rsa_context *ctx )
01472 {
01473     mpi_free( &ctx->Vi  ); mpi_free( &ctx->Vf  );
01474     mpi_free( &ctx->RQ  ); mpi_free( &ctx->RP  ); mpi_free( &ctx->RN  );
01475     mpi_free( &ctx->QP  ); mpi_free( &ctx->DQ  ); mpi_free( &ctx->DP  );
01476     mpi_free( &ctx->Q   ); mpi_free( &ctx->P   ); mpi_free( &ctx->D  );
01477     mpi_free( &ctx->E   ); mpi_free( &ctx->N   );
01478 
01479 #if defined(POLARSSL_THREADING_C)
01480     polarssl_mutex_free( &ctx->mutex  );
01481 #endif
01482 }
01483 
01484 #if defined(POLARSSL_SELF_TEST)
01485 
01486 #include "polarssl/sha1.h"
01487 
01488 /*
01489  * Example RSA-1024 keypair, for test purposes
01490  */
01491 #define KEY_LEN 128
01492 
01493 #define RSA_N   "9292758453063D803DD603D5E777D788" \
01494                 "8ED1D5BF35786190FA2F23EBC0848AEA" \
01495                 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
01496                 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
01497                 "93A89813FBF3C4F8066D2D800F7C38A8" \
01498                 "1AE31942917403FF4946B0A83D3D3E05" \
01499                 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
01500                 "5E94BB77B07507233A0BC7BAC8F90F79"
01501 
01502 #define RSA_E   "10001"
01503 
01504 #define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
01505                 "66CA472BC44D253102F8B4A9D3BFA750" \
01506                 "91386C0077937FE33FA3252D28855837" \
01507                 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
01508                 "DF79C5CE07EE72C7F123142198164234" \
01509                 "CABB724CF78B8173B9F880FC86322407" \
01510                 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
01511                 "071513A1E85B5DFA031F21ECAE91A34D"
01512 
01513 #define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
01514                 "2C01CAD19EA484A87EA4377637E75500" \
01515                 "FCB2005C5C7DD6EC4AC023CDA285D796" \
01516                 "C3D9E75E1EFC42488BB4F1D13AC30A57"
01517 
01518 #define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
01519                 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
01520                 "910E4168387E3C30AA1E00C339A79508" \
01521                 "8452DD96A9A5EA5D9DCA68DA636032AF"
01522 
01523 #define RSA_DP  "C1ACF567564274FB07A0BBAD5D26E298" \
01524                 "3C94D22288ACD763FD8E5600ED4A702D" \
01525                 "F84198A5F06C2E72236AE490C93F07F8" \
01526                 "3CC559CD27BC2D1CA488811730BB5725"
01527 
01528 #define RSA_DQ  "4959CBF6F8FEF750AEE6977C155579C7" \
01529                 "D8AAEA56749EA28623272E4F7D0592AF" \
01530                 "7C1F1313CAC9471B5C523BFE592F517B" \
01531                 "407A1BD76C164B93DA2D32A383E58357"
01532 
01533 #define RSA_QP  "9AE7FBC99546432DF71896FC239EADAE" \
01534                 "F38D18D2B2F0E2DD275AA977E2BF4411" \
01535                 "F5A3B2A5D33605AEBBCCBA7FEB9F2D2F" \
01536                 "A74206CEC169D74BF5A8C50D6F48EA08"
01537 
01538 #define PT_LEN  24
01539 #define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
01540                 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
01541 
01542 #if defined(POLARSSL_PKCS1_V15)
01543 static int myrand( void *rng_state, unsigned char *output, size_t len )
01544 {
01545 #if !defined(__OpenBSD__)
01546     size_t i;
01547 
01548     if( rng_state != NULL )
01549         rng_state  = NULL;
01550 
01551     for( i = 0; i < len; ++i )
01552         output[i] = rand();
01553 #else
01554     if( rng_state != NULL )
01555         rng_state = NULL;
01556 
01557     arc4random_buf( output, len );
01558 #endif /* !OpenBSD */
01559 
01560     return( 0 );
01561 }
01562 #endif /* POLARSSL_PKCS1_V15 */
01563 
01564 /*
01565  * Checkup routine
01566  */
01567 int rsa_self_test( int verbose )
01568 {
01569     int ret = 0;
01570 #if defined(POLARSSL_PKCS1_V15)
01571     size_t len;
01572     rsa_context rsa;
01573     unsigned char rsa_plaintext[PT_LEN];
01574     unsigned char rsa_decrypted[PT_LEN];
01575     unsigned char rsa_ciphertext[KEY_LEN];
01576 #if defined(POLARSSL_SHA1_C)
01577     unsigned char sha1sum[20];
01578 #endif
01579 
01580     rsa_init( &rsa, RSA_PKCS_V15, 0 );
01581 
01582     rsa.len  = KEY_LEN;
01583     MPI_CHK( mpi_read_string( &rsa.N  , 16, RSA_N  ) );
01584     MPI_CHK( mpi_read_string( &rsa.E  , 16, RSA_E  ) );
01585     MPI_CHK( mpi_read_string( &rsa.D  , 16, RSA_D  ) );
01586     MPI_CHK( mpi_read_string( &rsa.P  , 16, RSA_P  ) );
01587     MPI_CHK( mpi_read_string( &rsa.Q  , 16, RSA_Q  ) );
01588     MPI_CHK( mpi_read_string( &rsa.DP , 16, RSA_DP ) );
01589     MPI_CHK( mpi_read_string( &rsa.DQ , 16, RSA_DQ ) );
01590     MPI_CHK( mpi_read_string( &rsa.QP , 16, RSA_QP ) );
01591 
01592     if( verbose != 0 )
01593         polarssl_printf( "  RSA key validation: " );
01594 
01595     if( rsa_check_pubkey(  &rsa ) != 0 ||
01596         rsa_check_privkey( &rsa ) != 0 )
01597     {
01598         if( verbose != 0 )
01599             polarssl_printf( "failed\n" );
01600 
01601         return( 1 );
01602     }
01603 
01604     if( verbose != 0 )
01605         polarssl_printf( "passed\n  PKCS#1 encryption : " );
01606 
01607     memcpy( rsa_plaintext, RSA_PT, PT_LEN );
01608 
01609     if( rsa_pkcs1_encrypt( &rsa, myrand, NULL, RSA_PUBLIC, PT_LEN,
01610                            rsa_plaintext, rsa_ciphertext ) != 0 )
01611     {
01612         if( verbose != 0 )
01613             polarssl_printf( "failed\n" );
01614 
01615         return( 1 );
01616     }
01617 
01618     if( verbose != 0 )
01619         polarssl_printf( "passed\n  PKCS#1 decryption : " );
01620 
01621     if( rsa_pkcs1_decrypt( &rsa, myrand, NULL, RSA_PRIVATE, &len,
01622                            rsa_ciphertext, rsa_decrypted,
01623                            sizeof(rsa_decrypted) ) != 0 )
01624     {
01625         if( verbose != 0 )
01626             polarssl_printf( "failed\n" );
01627 
01628         return( 1 );
01629     }
01630 
01631     if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
01632     {
01633         if( verbose != 0 )
01634             polarssl_printf( "failed\n" );
01635 
01636         return( 1 );
01637     }
01638 
01639 #if defined(POLARSSL_SHA1_C)
01640     if( verbose != 0 )
01641         polarssl_printf( "passed\n  PKCS#1 data sign  : " );
01642 
01643     sha1( rsa_plaintext, PT_LEN, sha1sum );
01644 
01645     if( rsa_pkcs1_sign( &rsa, myrand, NULL, RSA_PRIVATE, POLARSSL_MD_SHA1, 0,
01646                         sha1sum, rsa_ciphertext ) != 0 )
01647     {
01648         if( verbose != 0 )
01649             polarssl_printf( "failed\n" );
01650 
01651         return( 1 );
01652     }
01653 
01654     if( verbose != 0 )
01655         polarssl_printf( "passed\n  PKCS#1 sig. verify: " );
01656 
01657     if( rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC, POLARSSL_MD_SHA1, 0,
01658                           sha1sum, rsa_ciphertext ) != 0 )
01659     {
01660         if( verbose != 0 )
01661             polarssl_printf( "failed\n" );
01662 
01663         return( 1 );
01664     }
01665 
01666     if( verbose != 0 )
01667         polarssl_printf( "passed\n\n" );
01668 #endif /* POLARSSL_SHA1_C */
01669 
01670 cleanup:
01671     rsa_free( &rsa );
01672 #else /* POLARSSL_PKCS1_V15 */
01673     ((void) verbose);
01674 #endif /* POLARSSL_PKCS1_V15 */
01675     return( ret );
01676 }
01677 
01678 #endif /* POLARSSL_SELF_TEST */
01679 
01680 #endif /* POLARSSL_RSA_C */
01681