Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  *  The RSA public-key cryptosystem
  3.  *
  4.  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5.  *  SPDX-License-Identifier: GPL-2.0
  6.  *
  7.  *  This program is free software; you can redistribute it and/or modify
  8.  *  it under the terms of the GNU General Public License as published by
  9.  *  the Free Software Foundation; either version 2 of the License, or
  10.  *  (at your option) any later version.
  11.  *
  12.  *  This program is distributed in the hope that it will be useful,
  13.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  *  GNU General Public License for more details.
  16.  *
  17.  *  You should have received a copy of the GNU General Public License along
  18.  *  with this program; if not, write to the Free Software Foundation, Inc.,
  19.  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20.  *
  21.  *  This file is part of mbed TLS (https://tls.mbed.org)
  22.  */
  23.  
  24. /*
  25.  *  The following sources were referenced in the design of this implementation
  26.  *  of the RSA algorithm:
  27.  *
  28.  *  [1] A method for obtaining digital signatures and public-key cryptosystems
  29.  *      R Rivest, A Shamir, and L Adleman
  30.  *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
  31.  *
  32.  *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
  33.  *      Menezes, van Oorschot and Vanstone
  34.  *
  35.  *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
  36.  *      Michael Schwarz, Samuel Weiser, Daniel Gruss, ClĂ©mentine Maurice and
  37.  *      Stefan Mangard
  38.  *      https://arxiv.org/abs/1702.08719v2
  39.  *
  40.  */
  41.  
  42. #if !defined(MBEDTLS_CONFIG_FILE)
  43. #include "mbedtls/config.h"
  44. #else
  45. #include MBEDTLS_CONFIG_FILE
  46. #endif
  47.  
  48. #if defined(MBEDTLS_RSA_C)
  49.  
  50. #include "mbedtls/rsa.h"
  51. #include "mbedtls/rsa_internal.h"
  52. #include "mbedtls/oid.h"
  53. #include "mbedtls/platform_util.h"
  54.  
  55. #include <string.h>
  56.  
  57. #if defined(MBEDTLS_PKCS1_V21)
  58. #include "mbedtls/md.h"
  59. #endif
  60.  
  61. #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)
  62. #include <stdlib.h>
  63. #endif
  64.  
  65. #if defined(MBEDTLS_PLATFORM_C)
  66. #include "mbedtls/platform.h"
  67. #else
  68. #include <stdio.h>
  69. #define mbedtls_printf printf
  70. #define mbedtls_calloc calloc
  71. #define mbedtls_free   free
  72. #endif
  73.  
  74. #if !defined(MBEDTLS_RSA_ALT)
  75.  
  76. /* Parameter validation macros */
  77. #define RSA_VALIDATE_RET( cond )                                       \
  78.     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
  79. #define RSA_VALIDATE( cond )                                           \
  80.     MBEDTLS_INTERNAL_VALIDATE( cond )
  81.  
  82. #if defined(MBEDTLS_PKCS1_V15)
  83. /* constant-time buffer comparison */
  84. static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
  85. {
  86.     size_t i;
  87.     const unsigned char *A = (const unsigned char *) a;
  88.     const unsigned char *B = (const unsigned char *) b;
  89.     unsigned char diff = 0;
  90.  
  91.     for( i = 0; i < n; i++ )
  92.         diff |= A[i] ^ B[i];
  93.  
  94.     return( diff );
  95. }
  96. #endif /* MBEDTLS_PKCS1_V15 */
  97.  
  98. int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
  99.                         const mbedtls_mpi *N,
  100.                         const mbedtls_mpi *P, const mbedtls_mpi *Q,
  101.                         const mbedtls_mpi *D, const mbedtls_mpi *E )
  102. {
  103.     int ret;
  104.     RSA_VALIDATE_RET( ctx != NULL );
  105.  
  106.     if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->N, N ) ) != 0 ) ||
  107.         ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ) ||
  108.         ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->Q, Q ) ) != 0 ) ||
  109.         ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->D, D ) ) != 0 ) ||
  110.         ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->E, E ) ) != 0 ) )
  111.     {
  112.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  113.     }
  114.  
  115.     if( N != NULL )
  116.         ctx->len = mbedtls_mpi_size( &ctx->N );
  117.  
  118.     return( 0 );
  119. }
  120.  
  121. int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,
  122.                             unsigned char const *N, size_t N_len,
  123.                             unsigned char const *P, size_t P_len,
  124.                             unsigned char const *Q, size_t Q_len,
  125.                             unsigned char const *D, size_t D_len,
  126.                             unsigned char const *E, size_t E_len )
  127. {
  128.     int ret = 0;
  129.     RSA_VALIDATE_RET( ctx != NULL );
  130.  
  131.     if( N != NULL )
  132.     {
  133.         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->N, N, N_len ) );
  134.         ctx->len = mbedtls_mpi_size( &ctx->N );
  135.     }
  136.  
  137.     if( P != NULL )
  138.         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->P, P, P_len ) );
  139.  
  140.     if( Q != NULL )
  141.         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->Q, Q, Q_len ) );
  142.  
  143.     if( D != NULL )
  144.         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->D, D, D_len ) );
  145.  
  146.     if( E != NULL )
  147.         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->E, E, E_len ) );
  148.  
  149. cleanup:
  150.  
  151.     if( ret != 0 )
  152.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  153.  
  154.     return( 0 );
  155. }
  156.  
  157. /*
  158.  * Checks whether the context fields are set in such a way
  159.  * that the RSA primitives will be able to execute without error.
  160.  * It does *not* make guarantees for consistency of the parameters.
  161.  */
  162. static int rsa_check_context( mbedtls_rsa_context const *ctx, int is_priv,
  163.                               int blinding_needed )
  164. {
  165. #if !defined(MBEDTLS_RSA_NO_CRT)
  166.     /* blinding_needed is only used for NO_CRT to decide whether
  167.      * P,Q need to be present or not. */
  168.     ((void) blinding_needed);
  169. #endif
  170.  
  171.     if( ctx->len != mbedtls_mpi_size( &ctx->N ) ||
  172.         ctx->len > MBEDTLS_MPI_MAX_SIZE )
  173.     {
  174.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  175.     }
  176.  
  177.     /*
  178.      * 1. Modular exponentiation needs positive, odd moduli.
  179.      */
  180.  
  181.     /* Modular exponentiation wrt. N is always used for
  182.      * RSA public key operations. */
  183.     if( mbedtls_mpi_cmp_int( &ctx->N, 0 ) <= 0 ||
  184.         mbedtls_mpi_get_bit( &ctx->N, 0 ) == 0  )
  185.     {
  186.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  187.     }
  188.  
  189. #if !defined(MBEDTLS_RSA_NO_CRT)
  190.     /* Modular exponentiation for P and Q is only
  191.      * used for private key operations and if CRT
  192.      * is used. */
  193.     if( is_priv &&
  194.         ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||
  195.           mbedtls_mpi_get_bit( &ctx->P, 0 ) == 0 ||
  196.           mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ||
  197.           mbedtls_mpi_get_bit( &ctx->Q, 0 ) == 0  ) )
  198.     {
  199.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  200.     }
  201. #endif /* !MBEDTLS_RSA_NO_CRT */
  202.  
  203.     /*
  204.      * 2. Exponents must be positive
  205.      */
  206.  
  207.     /* Always need E for public key operations */
  208.     if( mbedtls_mpi_cmp_int( &ctx->E, 0 ) <= 0 )
  209.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  210.  
  211. #if defined(MBEDTLS_RSA_NO_CRT)
  212.     /* For private key operations, use D or DP & DQ
  213.      * as (unblinded) exponents. */
  214.     if( is_priv && mbedtls_mpi_cmp_int( &ctx->D, 0 ) <= 0 )
  215.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  216. #else
  217.     if( is_priv &&
  218.         ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) <= 0 ||
  219.           mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) <= 0  ) )
  220.     {
  221.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  222.     }
  223. #endif /* MBEDTLS_RSA_NO_CRT */
  224.  
  225.     /* Blinding shouldn't make exponents negative either,
  226.      * so check that P, Q >= 1 if that hasn't yet been
  227.      * done as part of 1. */
  228. #if defined(MBEDTLS_RSA_NO_CRT)
  229.     if( is_priv && blinding_needed &&
  230.         ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) <= 0 ||
  231.           mbedtls_mpi_cmp_int( &ctx->Q, 0 ) <= 0 ) )
  232.     {
  233.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  234.     }
  235. #endif
  236.  
  237.     /* It wouldn't lead to an error if it wasn't satisfied,
  238.      * but check for QP >= 1 nonetheless. */
  239. #if !defined(MBEDTLS_RSA_NO_CRT)
  240.     if( is_priv &&
  241.         mbedtls_mpi_cmp_int( &ctx->QP, 0 ) <= 0 )
  242.     {
  243.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  244.     }
  245. #endif
  246.  
  247.     return( 0 );
  248. }
  249.  
  250. int mbedtls_rsa_complete( mbedtls_rsa_context *ctx )
  251. {
  252.     int ret = 0;
  253.     int have_N, have_P, have_Q, have_D, have_E;
  254. #if !defined(MBEDTLS_RSA_NO_CRT)
  255.     int have_DP, have_DQ, have_QP;
  256. #endif
  257.     int n_missing, pq_missing, d_missing, is_pub, is_priv;
  258.  
  259.     RSA_VALIDATE_RET( ctx != NULL );
  260.  
  261.     have_N = ( mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 );
  262.     have_P = ( mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 );
  263.     have_Q = ( mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 );
  264.     have_D = ( mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 );
  265.     have_E = ( mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0 );
  266.  
  267. #if !defined(MBEDTLS_RSA_NO_CRT)
  268.     have_DP = ( mbedtls_mpi_cmp_int( &ctx->DP, 0 ) != 0 );
  269.     have_DQ = ( mbedtls_mpi_cmp_int( &ctx->DQ, 0 ) != 0 );
  270.     have_QP = ( mbedtls_mpi_cmp_int( &ctx->QP, 0 ) != 0 );
  271. #endif
  272.  
  273.     /*
  274.      * Check whether provided parameters are enough
  275.      * to deduce all others. The following incomplete
  276.      * parameter sets for private keys are supported:
  277.      *
  278.      * (1) P, Q missing.
  279.      * (2) D and potentially N missing.
  280.      *
  281.      */
  282.  
  283.     n_missing  =              have_P &&  have_Q &&  have_D && have_E;
  284.     pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
  285.     d_missing  =              have_P &&  have_Q && !have_D && have_E;
  286.     is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
  287.  
  288.     /* These three alternatives are mutually exclusive */
  289.     is_priv = n_missing || pq_missing || d_missing;
  290.  
  291.     if( !is_priv && !is_pub )
  292.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  293.  
  294.     /*
  295.      * Step 1: Deduce N if P, Q are provided.
  296.      */
  297.  
  298.     if( !have_N && have_P && have_Q )
  299.     {
  300.         if( ( ret = mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P,
  301.                                          &ctx->Q ) ) != 0 )
  302.         {
  303.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  304.         }
  305.  
  306.         ctx->len = mbedtls_mpi_size( &ctx->N );
  307.     }
  308.  
  309.     /*
  310.      * Step 2: Deduce and verify all remaining core parameters.
  311.      */
  312.  
  313.     if( pq_missing )
  314.     {
  315.         ret = mbedtls_rsa_deduce_primes( &ctx->N, &ctx->E, &ctx->D,
  316.                                          &ctx->P, &ctx->Q );
  317.         if( ret != 0 )
  318.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  319.  
  320.     }
  321.     else if( d_missing )
  322.     {
  323.         if( ( ret = mbedtls_rsa_deduce_private_exponent( &ctx->P,
  324.                                                          &ctx->Q,
  325.                                                          &ctx->E,
  326.                                                          &ctx->D ) ) != 0 )
  327.         {
  328.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  329.         }
  330.     }
  331.  
  332.     /*
  333.      * Step 3: Deduce all additional parameters specific
  334.      *         to our current RSA implementation.
  335.      */
  336.  
  337. #if !defined(MBEDTLS_RSA_NO_CRT)
  338.     if( is_priv && ! ( have_DP && have_DQ && have_QP ) )
  339.     {
  340.         ret = mbedtls_rsa_deduce_crt( &ctx->P,  &ctx->Q,  &ctx->D,
  341.                                       &ctx->DP, &ctx->DQ, &ctx->QP );
  342.         if( ret != 0 )
  343.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  344.     }
  345. #endif /* MBEDTLS_RSA_NO_CRT */
  346.  
  347.     /*
  348.      * Step 3: Basic sanity checks
  349.      */
  350.  
  351.     return( rsa_check_context( ctx, is_priv, 1 ) );
  352. }
  353.  
  354. int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,
  355.                             unsigned char *N, size_t N_len,
  356.                             unsigned char *P, size_t P_len,
  357.                             unsigned char *Q, size_t Q_len,
  358.                             unsigned char *D, size_t D_len,
  359.                             unsigned char *E, size_t E_len )
  360. {
  361.     int ret = 0;
  362.     int is_priv;
  363.     RSA_VALIDATE_RET( ctx != NULL );
  364.  
  365.     /* Check if key is private or public */
  366.     is_priv =
  367.         mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  368.         mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  369.         mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  370.         mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  371.         mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  372.  
  373.     if( !is_priv )
  374.     {
  375.         /* If we're trying to export private parameters for a public key,
  376.          * something must be wrong. */
  377.         if( P != NULL || Q != NULL || D != NULL )
  378.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  379.  
  380.     }
  381.  
  382.     if( N != NULL )
  383.         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->N, N, N_len ) );
  384.  
  385.     if( P != NULL )
  386.         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->P, P, P_len ) );
  387.  
  388.     if( Q != NULL )
  389.         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->Q, Q, Q_len ) );
  390.  
  391.     if( D != NULL )
  392.         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->D, D, D_len ) );
  393.  
  394.     if( E != NULL )
  395.         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->E, E, E_len ) );
  396.  
  397. cleanup:
  398.  
  399.     return( ret );
  400. }
  401.  
  402. int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
  403.                         mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
  404.                         mbedtls_mpi *D, mbedtls_mpi *E )
  405. {
  406.     int ret;
  407.     int is_priv;
  408.     RSA_VALIDATE_RET( ctx != NULL );
  409.  
  410.     /* Check if key is private or public */
  411.     is_priv =
  412.         mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  413.         mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  414.         mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  415.         mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  416.         mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  417.  
  418.     if( !is_priv )
  419.     {
  420.         /* If we're trying to export private parameters for a public key,
  421.          * something must be wrong. */
  422.         if( P != NULL || Q != NULL || D != NULL )
  423.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  424.  
  425.     }
  426.  
  427.     /* Export all requested core parameters. */
  428.  
  429.     if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->N ) ) != 0 ) ||
  430.         ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->P ) ) != 0 ) ||
  431.         ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->Q ) ) != 0 ) ||
  432.         ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->D ) ) != 0 ) ||
  433.         ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->E ) ) != 0 ) )
  434.     {
  435.         return( ret );
  436.     }
  437.  
  438.     return( 0 );
  439. }
  440.  
  441. /*
  442.  * Export CRT parameters
  443.  * This must also be implemented if CRT is not used, for being able to
  444.  * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
  445.  * can be used in this case.
  446.  */
  447. int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
  448.                             mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )
  449. {
  450.     int ret;
  451.     int is_priv;
  452.     RSA_VALIDATE_RET( ctx != NULL );
  453.  
  454.     /* Check if key is private or public */
  455.     is_priv =
  456.         mbedtls_mpi_cmp_int( &ctx->N, 0 ) != 0 &&
  457.         mbedtls_mpi_cmp_int( &ctx->P, 0 ) != 0 &&
  458.         mbedtls_mpi_cmp_int( &ctx->Q, 0 ) != 0 &&
  459.         mbedtls_mpi_cmp_int( &ctx->D, 0 ) != 0 &&
  460.         mbedtls_mpi_cmp_int( &ctx->E, 0 ) != 0;
  461.  
  462.     if( !is_priv )
  463.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  464.  
  465. #if !defined(MBEDTLS_RSA_NO_CRT)
  466.     /* Export all requested blinding parameters. */
  467.     if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->DP ) ) != 0 ) ||
  468.         ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->DQ ) ) != 0 ) ||
  469.         ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->QP ) ) != 0 ) )
  470.     {
  471.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  472.     }
  473. #else
  474.     if( ( ret = mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,
  475.                                         DP, DQ, QP ) ) != 0 )
  476.     {
  477.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
  478.     }
  479. #endif
  480.  
  481.     return( 0 );
  482. }
  483.  
  484. /*
  485.  * Initialize an RSA context
  486.  */
  487. void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
  488.                int padding,
  489.                int hash_id )
  490. {
  491.     RSA_VALIDATE( ctx != NULL );
  492.     RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 ||
  493.                   padding == MBEDTLS_RSA_PKCS_V21 );
  494.  
  495.     memset( ctx, 0, sizeof( mbedtls_rsa_context ) );
  496.  
  497.     mbedtls_rsa_set_padding( ctx, padding, hash_id );
  498.  
  499. #if defined(MBEDTLS_THREADING_C)
  500.     mbedtls_mutex_init( &ctx->mutex );
  501. #endif
  502. }
  503.  
  504. /*
  505.  * Set padding for an existing RSA context
  506.  */
  507. void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding,
  508.                               int hash_id )
  509. {
  510.     RSA_VALIDATE( ctx != NULL );
  511.     RSA_VALIDATE( padding == MBEDTLS_RSA_PKCS_V15 ||
  512.                   padding == MBEDTLS_RSA_PKCS_V21 );
  513.  
  514.     ctx->padding = padding;
  515.     ctx->hash_id = hash_id;
  516. }
  517.  
  518. /*
  519.  * Get length in bytes of RSA modulus
  520.  */
  521.  
  522. size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )
  523. {
  524.     return( ctx->len );
  525. }
  526.  
  527.  
  528. #if defined(MBEDTLS_GENPRIME)
  529.  
  530. /*
  531.  * Generate an RSA keypair
  532.  *
  533.  * This generation method follows the RSA key pair generation procedure of
  534.  * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
  535.  */
  536. int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
  537.                  int (*f_rng)(void *, unsigned char *, size_t),
  538.                  void *p_rng,
  539.                  unsigned int nbits, int exponent )
  540. {
  541.     int ret;
  542.     mbedtls_mpi H, G, L;
  543.     int prime_quality = 0;
  544.     RSA_VALIDATE_RET( ctx != NULL );
  545.     RSA_VALIDATE_RET( f_rng != NULL );
  546.  
  547.     if( nbits < 128 || exponent < 3 || nbits % 2 != 0 )
  548.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  549.  
  550.     /*
  551.      * If the modulus is 1024 bit long or shorter, then the security strength of
  552.      * the RSA algorithm is less than or equal to 80 bits and therefore an error
  553.      * rate of 2^-80 is sufficient.
  554.      */
  555.     if( nbits > 1024 )
  556.         prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
  557.  
  558.     mbedtls_mpi_init( &H );
  559.     mbedtls_mpi_init( &G );
  560.     mbedtls_mpi_init( &L );
  561.  
  562.     /*
  563.      * find primes P and Q with Q < P so that:
  564.      * 1.  |P-Q| > 2^( nbits / 2 - 100 )
  565.      * 2.  GCD( E, (P-1)*(Q-1) ) == 1
  566.      * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
  567.      */
  568.     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &ctx->E, exponent ) );
  569.  
  570.     do
  571.     {
  572.         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1,
  573.                                                 prime_quality, f_rng, p_rng ) );
  574.  
  575.         MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1,
  576.                                                 prime_quality, f_rng, p_rng ) );
  577.  
  578.         /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
  579.         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) );
  580.         if( mbedtls_mpi_bitlen( &H ) <= ( ( nbits >= 200 ) ? ( ( nbits >> 1 ) - 99 ) : 0 ) )
  581.             continue;
  582.  
  583.         /* not required by any standards, but some users rely on the fact that P > Q */
  584.         if( H.s < 0 )
  585.             mbedtls_mpi_swap( &ctx->P, &ctx->Q );
  586.  
  587.         /* Temporarily replace P,Q by P-1, Q-1 */
  588.         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->P, &ctx->P, 1 ) );
  589.         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &ctx->Q, &ctx->Q, 1 ) );
  590.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &H, &ctx->P, &ctx->Q ) );
  591.  
  592.         /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
  593.         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->E, &H  ) );
  594.         if( mbedtls_mpi_cmp_int( &G, 1 ) != 0 )
  595.             continue;
  596.  
  597.         /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
  598.         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &G, &ctx->P, &ctx->Q ) );
  599.         MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &L, NULL, &H, &G ) );
  600.         MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->D, &ctx->E, &L ) );
  601.  
  602.         if( mbedtls_mpi_bitlen( &ctx->D ) <= ( ( nbits + 1 ) / 2 ) ) // (FIPS 186-4 §B.3.1 criterion 3(a))
  603.             continue;
  604.  
  605.         break;
  606.     }
  607.     while( 1 );
  608.  
  609.     /* Restore P,Q */
  610.     MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->P,  &ctx->P, 1 ) );
  611.     MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &ctx->Q,  &ctx->Q, 1 ) );
  612.  
  613.     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->N, &ctx->P, &ctx->Q ) );
  614.  
  615.     ctx->len = mbedtls_mpi_size( &ctx->N );
  616.  
  617. #if !defined(MBEDTLS_RSA_NO_CRT)
  618.     /*
  619.      * DP = D mod (P - 1)
  620.      * DQ = D mod (Q - 1)
  621.      * QP = Q^-1 mod P
  622.      */
  623.     MBEDTLS_MPI_CHK( mbedtls_rsa_deduce_crt( &ctx->P, &ctx->Q, &ctx->D,
  624.                                              &ctx->DP, &ctx->DQ, &ctx->QP ) );
  625. #endif /* MBEDTLS_RSA_NO_CRT */
  626.  
  627.     /* Double-check */
  628.     MBEDTLS_MPI_CHK( mbedtls_rsa_check_privkey( ctx ) );
  629.  
  630. cleanup:
  631.  
  632.     mbedtls_mpi_free( &H );
  633.     mbedtls_mpi_free( &G );
  634.     mbedtls_mpi_free( &L );
  635.  
  636.     if( ret != 0 )
  637.     {
  638.         mbedtls_rsa_free( ctx );
  639.         return( MBEDTLS_ERR_RSA_KEY_GEN_FAILED + ret );
  640.     }
  641.  
  642.     return( 0 );
  643. }
  644.  
  645. #endif /* MBEDTLS_GENPRIME */
  646.  
  647. /*
  648.  * Check a public RSA key
  649.  */
  650. int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )
  651. {
  652.     RSA_VALIDATE_RET( ctx != NULL );
  653.  
  654.     if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) != 0 )
  655.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  656.  
  657.     if( mbedtls_mpi_bitlen( &ctx->N ) < 128 )
  658.     {
  659.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  660.     }
  661.  
  662.     if( mbedtls_mpi_get_bit( &ctx->E, 0 ) == 0 ||
  663.         mbedtls_mpi_bitlen( &ctx->E )     < 2  ||
  664.         mbedtls_mpi_cmp_mpi( &ctx->E, &ctx->N ) >= 0 )
  665.     {
  666.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  667.     }
  668.  
  669.     return( 0 );
  670. }
  671.  
  672. /*
  673.  * Check for the consistency of all fields in an RSA private key context
  674.  */
  675. int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )
  676. {
  677.     RSA_VALIDATE_RET( ctx != NULL );
  678.  
  679.     if( mbedtls_rsa_check_pubkey( ctx ) != 0 ||
  680.         rsa_check_context( ctx, 1 /* private */, 1 /* blinding */ ) != 0 )
  681.     {
  682.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  683.     }
  684.  
  685.     if( mbedtls_rsa_validate_params( &ctx->N, &ctx->P, &ctx->Q,
  686.                                      &ctx->D, &ctx->E, NULL, NULL ) != 0 )
  687.     {
  688.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  689.     }
  690.  
  691. #if !defined(MBEDTLS_RSA_NO_CRT)
  692.     else if( mbedtls_rsa_validate_crt( &ctx->P, &ctx->Q, &ctx->D,
  693.                                        &ctx->DP, &ctx->DQ, &ctx->QP ) != 0 )
  694.     {
  695.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  696.     }
  697. #endif
  698.  
  699.     return( 0 );
  700. }
  701.  
  702. /*
  703.  * Check if contexts holding a public and private key match
  704.  */
  705. int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,
  706.                                 const mbedtls_rsa_context *prv )
  707. {
  708.     RSA_VALIDATE_RET( pub != NULL );
  709.     RSA_VALIDATE_RET( prv != NULL );
  710.  
  711.     if( mbedtls_rsa_check_pubkey( pub )  != 0 ||
  712.         mbedtls_rsa_check_privkey( prv ) != 0 )
  713.     {
  714.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  715.     }
  716.  
  717.     if( mbedtls_mpi_cmp_mpi( &pub->N, &prv->N ) != 0 ||
  718.         mbedtls_mpi_cmp_mpi( &pub->E, &prv->E ) != 0 )
  719.     {
  720.         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
  721.     }
  722.  
  723.     return( 0 );
  724. }
  725.  
  726. /*
  727.  * Do an RSA public key operation
  728.  */
  729. int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
  730.                 const unsigned char *input,
  731.                 unsigned char *output )
  732. {
  733.     int ret;
  734.     size_t olen;
  735.     mbedtls_mpi T;
  736.     RSA_VALIDATE_RET( ctx != NULL );
  737.     RSA_VALIDATE_RET( input != NULL );
  738.     RSA_VALIDATE_RET( output != NULL );
  739.  
  740.     if( rsa_check_context( ctx, 0 /* public */, 0 /* no blinding */ ) )
  741.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  742.  
  743.     mbedtls_mpi_init( &T );
  744.  
  745. #if defined(MBEDTLS_THREADING_C)
  746.     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
  747.         return( ret );
  748. #endif
  749.  
  750.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
  751.  
  752.     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
  753.     {
  754.         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  755.         goto cleanup;
  756.     }
  757.  
  758.     olen = ctx->len;
  759.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, &ctx->E, &ctx->N, &ctx->RN ) );
  760.     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
  761.  
  762. cleanup:
  763. #if defined(MBEDTLS_THREADING_C)
  764.     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
  765.         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
  766. #endif
  767.  
  768.     mbedtls_mpi_free( &T );
  769.  
  770.     if( ret != 0 )
  771.         return( MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret );
  772.  
  773.     return( 0 );
  774. }
  775.  
  776. /*
  777.  * Generate or update blinding values, see section 10 of:
  778.  *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
  779.  *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
  780.  *  Berlin Heidelberg, 1996. p. 104-113.
  781.  */
  782. static int rsa_prepare_blinding( mbedtls_rsa_context *ctx,
  783.                  int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
  784. {
  785.     int ret, count = 0;
  786.  
  787.     if( ctx->Vf.p != NULL )
  788.     {
  789.         /* We already have blinding values, just update them by squaring */
  790.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &ctx->Vi ) );
  791.         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) );
  792.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &ctx->Vf ) );
  793.         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->N ) );
  794.  
  795.         goto cleanup;
  796.     }
  797.  
  798.     /* Unblinding value: Vf = random number, invertible mod N */
  799.     do {
  800.         if( count++ > 10 )
  801.             return( MBEDTLS_ERR_RSA_RNG_FAILED );
  802.  
  803.         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) );
  804.         MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi, &ctx->Vf, &ctx->N ) );
  805.     } while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 );
  806.  
  807.     /* Blinding value: Vi =  Vf^(-e) mod N */
  808.     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) );
  809.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) );
  810.  
  811.  
  812. cleanup:
  813.     return( ret );
  814. }
  815.  
  816. /*
  817.  * Exponent blinding supposed to prevent side-channel attacks using multiple
  818.  * traces of measurements to recover the RSA key. The more collisions are there,
  819.  * the more bits of the key can be recovered. See [3].
  820.  *
  821.  * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
  822.  * observations on avarage.
  823.  *
  824.  * For example with 28 byte blinding to achieve 2 collisions the adversary has
  825.  * to make 2^112 observations on avarage.
  826.  *
  827.  * (With the currently (as of 2017 April) known best algorithms breaking 2048
  828.  * bit RSA requires approximately as much time as trying out 2^112 random keys.
  829.  * Thus in this sense with 28 byte blinding the security is not reduced by
  830.  * side-channel attacks like the one in [3])
  831.  *
  832.  * This countermeasure does not help if the key recovery is possible with a
  833.  * single trace.
  834.  */
  835. #define RSA_EXPONENT_BLINDING 28
  836.  
  837. /*
  838.  * Do an RSA private key operation
  839.  */
  840. int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
  841.                  int (*f_rng)(void *, unsigned char *, size_t),
  842.                  void *p_rng,
  843.                  const unsigned char *input,
  844.                  unsigned char *output )
  845. {
  846.     int ret;
  847.     size_t olen;
  848.  
  849.     /* Temporary holding the result */
  850.     mbedtls_mpi T;
  851.  
  852.     /* Temporaries holding P-1, Q-1 and the
  853.      * exponent blinding factor, respectively. */
  854.     mbedtls_mpi P1, Q1, R;
  855.  
  856. #if !defined(MBEDTLS_RSA_NO_CRT)
  857.     /* Temporaries holding the results mod p resp. mod q. */
  858.     mbedtls_mpi TP, TQ;
  859.  
  860.     /* Temporaries holding the blinded exponents for
  861.      * the mod p resp. mod q computation (if used). */
  862.     mbedtls_mpi DP_blind, DQ_blind;
  863.  
  864.     /* Pointers to actual exponents to be used - either the unblinded
  865.      * or the blinded ones, depending on the presence of a PRNG. */
  866.     mbedtls_mpi *DP = &ctx->DP;
  867.     mbedtls_mpi *DQ = &ctx->DQ;
  868. #else
  869.     /* Temporary holding the blinded exponent (if used). */
  870.     mbedtls_mpi D_blind;
  871.  
  872.     /* Pointer to actual exponent to be used - either the unblinded
  873.      * or the blinded one, depending on the presence of a PRNG. */
  874.     mbedtls_mpi *D = &ctx->D;
  875. #endif /* MBEDTLS_RSA_NO_CRT */
  876.  
  877.     /* Temporaries holding the initial input and the double
  878.      * checked result; should be the same in the end. */
  879.     mbedtls_mpi I, C;
  880.  
  881.     RSA_VALIDATE_RET( ctx != NULL );
  882.     RSA_VALIDATE_RET( input  != NULL );
  883.     RSA_VALIDATE_RET( output != NULL );
  884.  
  885.     if( rsa_check_context( ctx, 1             /* private key checks */,
  886.                                 f_rng != NULL /* blinding y/n       */ ) != 0 )
  887.     {
  888.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  889.     }
  890.  
  891. #if defined(MBEDTLS_THREADING_C)
  892.     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
  893.         return( ret );
  894. #endif
  895.  
  896.     /* MPI Initialization */
  897.     mbedtls_mpi_init( &T );
  898.  
  899.     mbedtls_mpi_init( &P1 );
  900.     mbedtls_mpi_init( &Q1 );
  901.     mbedtls_mpi_init( &R );
  902.  
  903.     if( f_rng != NULL )
  904.     {
  905. #if defined(MBEDTLS_RSA_NO_CRT)
  906.         mbedtls_mpi_init( &D_blind );
  907. #else
  908.         mbedtls_mpi_init( &DP_blind );
  909.         mbedtls_mpi_init( &DQ_blind );
  910. #endif
  911.     }
  912.  
  913. #if !defined(MBEDTLS_RSA_NO_CRT)
  914.     mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ );
  915. #endif
  916.  
  917.     mbedtls_mpi_init( &I );
  918.     mbedtls_mpi_init( &C );
  919.  
  920.     /* End of MPI initialization */
  921.  
  922.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
  923.     if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
  924.     {
  925.         ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  926.         goto cleanup;
  927.     }
  928.  
  929.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) );
  930.  
  931.     if( f_rng != NULL )
  932.     {
  933.         /*
  934.          * Blinding
  935.          * T = T * Vi mod N
  936.          */
  937.         MBEDTLS_MPI_CHK( rsa_prepare_blinding( ctx, f_rng, p_rng ) );
  938.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vi ) );
  939.         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
  940.  
  941.         /*
  942.          * Exponent blinding
  943.          */
  944.         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &P1, &ctx->P, 1 ) );
  945.         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &Q1, &ctx->Q, 1 ) );
  946.  
  947. #if defined(MBEDTLS_RSA_NO_CRT)
  948.         /*
  949.          * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
  950.          */
  951.         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  952.                          f_rng, p_rng ) );
  953.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &P1, &Q1 ) );
  954.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &D_blind, &D_blind, &R ) );
  955.         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &D_blind, &D_blind, &ctx->D ) );
  956.  
  957.         D = &D_blind;
  958. #else
  959.         /*
  960.          * DP_blind = ( P - 1 ) * R + DP
  961.          */
  962.         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  963.                          f_rng, p_rng ) );
  964.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DP_blind, &P1, &R ) );
  965.         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DP_blind, &DP_blind,
  966.                     &ctx->DP ) );
  967.  
  968.         DP = &DP_blind;
  969.  
  970.         /*
  971.          * DQ_blind = ( Q - 1 ) * R + DQ
  972.          */
  973.         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, RSA_EXPONENT_BLINDING,
  974.                          f_rng, p_rng ) );
  975.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DQ_blind, &Q1, &R ) );
  976.         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &DQ_blind, &DQ_blind,
  977.                     &ctx->DQ ) );
  978.  
  979.         DQ = &DQ_blind;
  980. #endif /* MBEDTLS_RSA_NO_CRT */
  981.     }
  982.  
  983. #if defined(MBEDTLS_RSA_NO_CRT)
  984.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T, &T, D, &ctx->N, &ctx->RN ) );
  985. #else
  986.     /*
  987.      * Faster decryption using the CRT
  988.      *
  989.      * TP = input ^ dP mod P
  990.      * TQ = input ^ dQ mod Q
  991.      */
  992.  
  993.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) );
  994.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) );
  995.  
  996.     /*
  997.      * T = (TP - TQ) * (Q^-1 mod P) mod P
  998.      */
  999.     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) );
  1000.     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) );
  1001.     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) );
  1002.  
  1003.     /*
  1004.      * T = TQ + T * Q
  1005.      */
  1006.     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) );
  1007.     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) );
  1008. #endif /* MBEDTLS_RSA_NO_CRT */
  1009.  
  1010.     if( f_rng != NULL )
  1011.     {
  1012.         /*
  1013.          * Unblind
  1014.          * T = T * Vf mod N
  1015.          */
  1016.         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, &T, &ctx->Vf ) );
  1017.         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
  1018.     }
  1019.  
  1020.     /* Verify the result to prevent glitching attacks. */
  1021.     MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E,
  1022.                                           &ctx->N, &ctx->RN ) );
  1023.     if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 )
  1024.     {
  1025.         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  1026.         goto cleanup;
  1027.     }
  1028.  
  1029.     olen = ctx->len;
  1030.     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
  1031.  
  1032. cleanup:
  1033. #if defined(MBEDTLS_THREADING_C)
  1034.     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
  1035.         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
  1036. #endif
  1037.  
  1038.     mbedtls_mpi_free( &P1 );
  1039.     mbedtls_mpi_free( &Q1 );
  1040.     mbedtls_mpi_free( &R );
  1041.  
  1042.     if( f_rng != NULL )
  1043.     {
  1044. #if defined(MBEDTLS_RSA_NO_CRT)
  1045.         mbedtls_mpi_free( &D_blind );
  1046. #else
  1047.         mbedtls_mpi_free( &DP_blind );
  1048.         mbedtls_mpi_free( &DQ_blind );
  1049. #endif
  1050.     }
  1051.  
  1052.     mbedtls_mpi_free( &T );
  1053.  
  1054. #if !defined(MBEDTLS_RSA_NO_CRT)
  1055.     mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ );
  1056. #endif
  1057.  
  1058.     mbedtls_mpi_free( &C );
  1059.     mbedtls_mpi_free( &I );
  1060.  
  1061.     if( ret != 0 )
  1062.         return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret );
  1063.  
  1064.     return( 0 );
  1065. }
  1066.  
  1067. #if defined(MBEDTLS_PKCS1_V21)
  1068. /**
  1069.  * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
  1070.  *
  1071.  * \param dst       buffer to mask
  1072.  * \param dlen      length of destination buffer
  1073.  * \param src       source of the mask generation
  1074.  * \param slen      length of the source buffer
  1075.  * \param md_ctx    message digest context to use
  1076.  */
  1077. static int mgf_mask( unsigned char *dst, size_t dlen, unsigned char *src,
  1078.                       size_t slen, mbedtls_md_context_t *md_ctx )
  1079. {
  1080.     unsigned char mask[MBEDTLS_MD_MAX_SIZE];
  1081.     unsigned char counter[4];
  1082.     unsigned char *p;
  1083.     unsigned int hlen;
  1084.     size_t i, use_len;
  1085.     int ret = 0;
  1086.  
  1087.     memset( mask, 0, MBEDTLS_MD_MAX_SIZE );
  1088.     memset( counter, 0, 4 );
  1089.  
  1090.     hlen = mbedtls_md_get_size( md_ctx->md_info );
  1091.  
  1092.     /* Generate and apply dbMask */
  1093.     p = dst;
  1094.  
  1095.     while( dlen > 0 )
  1096.     {
  1097.         use_len = hlen;
  1098.         if( dlen < hlen )
  1099.             use_len = dlen;
  1100.  
  1101.         if( ( ret = mbedtls_md_starts( md_ctx ) ) != 0 )
  1102.             goto exit;
  1103.         if( ( ret = mbedtls_md_update( md_ctx, src, slen ) ) != 0 )
  1104.             goto exit;
  1105.         if( ( ret = mbedtls_md_update( md_ctx, counter, 4 ) ) != 0 )
  1106.             goto exit;
  1107.         if( ( ret = mbedtls_md_finish( md_ctx, mask ) ) != 0 )
  1108.             goto exit;
  1109.  
  1110.         for( i = 0; i < use_len; ++i )
  1111.             *p++ ^= mask[i];
  1112.  
  1113.         counter[3]++;
  1114.  
  1115.         dlen -= use_len;
  1116.     }
  1117.  
  1118. exit:
  1119.     mbedtls_platform_zeroize( mask, sizeof( mask ) );
  1120.  
  1121.     return( ret );
  1122. }
  1123. #endif /* MBEDTLS_PKCS1_V21 */
  1124.  
  1125. #if defined(MBEDTLS_PKCS1_V21)
  1126. /*
  1127.  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
  1128.  */
  1129. int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
  1130.                             int (*f_rng)(void *, unsigned char *, size_t),
  1131.                             void *p_rng,
  1132.                             int mode,
  1133.                             const unsigned char *label, size_t label_len,
  1134.                             size_t ilen,
  1135.                             const unsigned char *input,
  1136.                             unsigned char *output )
  1137. {
  1138.     size_t olen;
  1139.     int ret;
  1140.     unsigned char *p = output;
  1141.     unsigned int hlen;
  1142.     const mbedtls_md_info_t *md_info;
  1143.     mbedtls_md_context_t md_ctx;
  1144.  
  1145.     RSA_VALIDATE_RET( ctx != NULL );
  1146.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1147.                       mode == MBEDTLS_RSA_PUBLIC );
  1148.     RSA_VALIDATE_RET( output != NULL );
  1149.     RSA_VALIDATE_RET( input != NULL );
  1150.     RSA_VALIDATE_RET( label_len == 0 || label != NULL );
  1151.  
  1152.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1153.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1154.  
  1155.     if( f_rng == NULL )
  1156.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1157.  
  1158.     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  1159.     if( md_info == NULL )
  1160.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1161.  
  1162.     olen = ctx->len;
  1163.     hlen = mbedtls_md_get_size( md_info );
  1164.  
  1165.     /* first comparison checks for overflow */
  1166.     if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
  1167.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1168.  
  1169.     memset( output, 0, olen );
  1170.  
  1171.     *p++ = 0;
  1172.  
  1173.     /* Generate a random octet string seed */
  1174.     if( ( ret = f_rng( p_rng, p, hlen ) ) != 0 )
  1175.         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
  1176.  
  1177.     p += hlen;
  1178.  
  1179.     /* Construct DB */
  1180.     if( ( ret = mbedtls_md( md_info, label, label_len, p ) ) != 0 )
  1181.         return( ret );
  1182.     p += hlen;
  1183.     p += olen - 2 * hlen - 2 - ilen;
  1184.     *p++ = 1;
  1185.     memcpy( p, input, ilen );
  1186.  
  1187.     mbedtls_md_init( &md_ctx );
  1188.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1189.         goto exit;
  1190.  
  1191.     /* maskedDB: Apply dbMask to DB */
  1192.     if( ( ret = mgf_mask( output + hlen + 1, olen - hlen - 1, output + 1, hlen,
  1193.                           &md_ctx ) ) != 0 )
  1194.         goto exit;
  1195.  
  1196.     /* maskedSeed: Apply seedMask to seed */
  1197.     if( ( ret = mgf_mask( output + 1, hlen, output + hlen + 1, olen - hlen - 1,
  1198.                           &md_ctx ) ) != 0 )
  1199.         goto exit;
  1200.  
  1201. exit:
  1202.     mbedtls_md_free( &md_ctx );
  1203.  
  1204.     if( ret != 0 )
  1205.         return( ret );
  1206.  
  1207.     return( ( mode == MBEDTLS_RSA_PUBLIC )
  1208.             ? mbedtls_rsa_public(  ctx, output, output )
  1209.             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
  1210. }
  1211. #endif /* MBEDTLS_PKCS1_V21 */
  1212.  
  1213. #if defined(MBEDTLS_PKCS1_V15)
  1214. /*
  1215.  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
  1216.  */
  1217. int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
  1218.                                  int (*f_rng)(void *, unsigned char *, size_t),
  1219.                                  void *p_rng,
  1220.                                  int mode, size_t ilen,
  1221.                                  const unsigned char *input,
  1222.                                  unsigned char *output )
  1223. {
  1224.     size_t nb_pad, olen;
  1225.     int ret;
  1226.     unsigned char *p = output;
  1227.  
  1228.     RSA_VALIDATE_RET( ctx != NULL );
  1229.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1230.                       mode == MBEDTLS_RSA_PUBLIC );
  1231.     RSA_VALIDATE_RET( output != NULL );
  1232.     RSA_VALIDATE_RET( input != NULL );
  1233.  
  1234.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  1235.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1236.  
  1237.     olen = ctx->len;
  1238.  
  1239.     /* first comparison checks for overflow */
  1240.     if( ilen + 11 < ilen || olen < ilen + 11 )
  1241.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1242.  
  1243.     nb_pad = olen - 3 - ilen;
  1244.  
  1245.     *p++ = 0;
  1246.     if( mode == MBEDTLS_RSA_PUBLIC )
  1247.     {
  1248.         if( f_rng == NULL )
  1249.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1250.  
  1251.         *p++ = MBEDTLS_RSA_CRYPT;
  1252.  
  1253.         while( nb_pad-- > 0 )
  1254.         {
  1255.             int rng_dl = 100;
  1256.  
  1257.             do {
  1258.                 ret = f_rng( p_rng, p, 1 );
  1259.             } while( *p == 0 && --rng_dl && ret == 0 );
  1260.  
  1261.             /* Check if RNG failed to generate data */
  1262.             if( rng_dl == 0 || ret != 0 )
  1263.                 return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
  1264.  
  1265.             p++;
  1266.         }
  1267.     }
  1268.     else
  1269.     {
  1270.         *p++ = MBEDTLS_RSA_SIGN;
  1271.  
  1272.         while( nb_pad-- > 0 )
  1273.             *p++ = 0xFF;
  1274.     }
  1275.  
  1276.     *p++ = 0;
  1277.     memcpy( p, input, ilen );
  1278.  
  1279.     return( ( mode == MBEDTLS_RSA_PUBLIC )
  1280.             ? mbedtls_rsa_public(  ctx, output, output )
  1281.             : mbedtls_rsa_private( ctx, f_rng, p_rng, output, output ) );
  1282. }
  1283. #endif /* MBEDTLS_PKCS1_V15 */
  1284.  
  1285. /*
  1286.  * Add the message padding, then do an RSA operation
  1287.  */
  1288. int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
  1289.                        int (*f_rng)(void *, unsigned char *, size_t),
  1290.                        void *p_rng,
  1291.                        int mode, size_t ilen,
  1292.                        const unsigned char *input,
  1293.                        unsigned char *output )
  1294. {
  1295.     RSA_VALIDATE_RET( ctx != NULL );
  1296.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1297.                       mode == MBEDTLS_RSA_PUBLIC );
  1298.     RSA_VALIDATE_RET( output != NULL );
  1299.     RSA_VALIDATE_RET( input != NULL );
  1300.  
  1301.     switch( ctx->padding )
  1302.     {
  1303. #if defined(MBEDTLS_PKCS1_V15)
  1304.         case MBEDTLS_RSA_PKCS_V15:
  1305.             return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, mode, ilen,
  1306.                                                 input, output );
  1307. #endif
  1308.  
  1309. #if defined(MBEDTLS_PKCS1_V21)
  1310.         case MBEDTLS_RSA_PKCS_V21:
  1311.             return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, mode, NULL, 0,
  1312.                                            ilen, input, output );
  1313. #endif
  1314.  
  1315.         default:
  1316.             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1317.     }
  1318. }
  1319.  
  1320. #if defined(MBEDTLS_PKCS1_V21)
  1321. /*
  1322.  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
  1323.  */
  1324. int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
  1325.                             int (*f_rng)(void *, unsigned char *, size_t),
  1326.                             void *p_rng,
  1327.                             int mode,
  1328.                             const unsigned char *label, size_t label_len,
  1329.                             size_t *olen,
  1330.                             const unsigned char *input,
  1331.                             unsigned char *output,
  1332.                             size_t output_max_len )
  1333. {
  1334.     int ret;
  1335.     size_t ilen, i, pad_len;
  1336.     unsigned char *p, bad, pad_done;
  1337.     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1338.     unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
  1339.     unsigned int hlen;
  1340.     const mbedtls_md_info_t *md_info;
  1341.     mbedtls_md_context_t md_ctx;
  1342.  
  1343.     RSA_VALIDATE_RET( ctx != NULL );
  1344.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1345.                       mode == MBEDTLS_RSA_PUBLIC );
  1346.     RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1347.     RSA_VALIDATE_RET( label_len == 0 || label != NULL );
  1348.     RSA_VALIDATE_RET( input != NULL );
  1349.     RSA_VALIDATE_RET( olen != NULL );
  1350.  
  1351.     /*
  1352.      * Parameters sanity checks
  1353.      */
  1354.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1355.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1356.  
  1357.     ilen = ctx->len;
  1358.  
  1359.     if( ilen < 16 || ilen > sizeof( buf ) )
  1360.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1361.  
  1362.     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  1363.     if( md_info == NULL )
  1364.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1365.  
  1366.     hlen = mbedtls_md_get_size( md_info );
  1367.  
  1368.     // checking for integer underflow
  1369.     if( 2 * hlen + 2 > ilen )
  1370.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1371.  
  1372.     /*
  1373.      * RSA operation
  1374.      */
  1375.     ret = ( mode == MBEDTLS_RSA_PUBLIC )
  1376.           ? mbedtls_rsa_public(  ctx, input, buf )
  1377.           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
  1378.  
  1379.     if( ret != 0 )
  1380.         goto cleanup;
  1381.  
  1382.     /*
  1383.      * Unmask data and generate lHash
  1384.      */
  1385.     mbedtls_md_init( &md_ctx );
  1386.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1387.     {
  1388.         mbedtls_md_free( &md_ctx );
  1389.         goto cleanup;
  1390.     }
  1391.  
  1392.     /* seed: Apply seedMask to maskedSeed */
  1393.     if( ( ret = mgf_mask( buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
  1394.                           &md_ctx ) ) != 0 ||
  1395.     /* DB: Apply dbMask to maskedDB */
  1396.         ( ret = mgf_mask( buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
  1397.                           &md_ctx ) ) != 0 )
  1398.     {
  1399.         mbedtls_md_free( &md_ctx );
  1400.         goto cleanup;
  1401.     }
  1402.  
  1403.     mbedtls_md_free( &md_ctx );
  1404.  
  1405.     /* Generate lHash */
  1406.     if( ( ret = mbedtls_md( md_info, label, label_len, lhash ) ) != 0 )
  1407.         goto cleanup;
  1408.  
  1409.     /*
  1410.      * Check contents, in "constant-time"
  1411.      */
  1412.     p = buf;
  1413.     bad = 0;
  1414.  
  1415.     bad |= *p++; /* First byte must be 0 */
  1416.  
  1417.     p += hlen; /* Skip seed */
  1418.  
  1419.     /* Check lHash */
  1420.     for( i = 0; i < hlen; i++ )
  1421.         bad |= lhash[i] ^ *p++;
  1422.  
  1423.     /* Get zero-padding len, but always read till end of buffer
  1424.      * (minus one, for the 01 byte) */
  1425.     pad_len = 0;
  1426.     pad_done = 0;
  1427.     for( i = 0; i < ilen - 2 * hlen - 2; i++ )
  1428.     {
  1429.         pad_done |= p[i];
  1430.         pad_len += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  1431.     }
  1432.  
  1433.     p += pad_len;
  1434.     bad |= *p++ ^ 0x01;
  1435.  
  1436.     /*
  1437.      * The only information "leaked" is whether the padding was correct or not
  1438.      * (eg, no data is copied if it was not correct). This meets the
  1439.      * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
  1440.      * the different error conditions.
  1441.      */
  1442.     if( bad != 0 )
  1443.     {
  1444.         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1445.         goto cleanup;
  1446.     }
  1447.  
  1448.     if( ilen - ( p - buf ) > output_max_len )
  1449.     {
  1450.         ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
  1451.         goto cleanup;
  1452.     }
  1453.  
  1454.     *olen = ilen - (p - buf);
  1455.     memcpy( output, p, *olen );
  1456.     ret = 0;
  1457.  
  1458. cleanup:
  1459.     mbedtls_platform_zeroize( buf, sizeof( buf ) );
  1460.     mbedtls_platform_zeroize( lhash, sizeof( lhash ) );
  1461.  
  1462.     return( ret );
  1463. }
  1464. #endif /* MBEDTLS_PKCS1_V21 */
  1465.  
  1466. #if defined(MBEDTLS_PKCS1_V15)
  1467. /** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
  1468.  *
  1469.  * \param value     The value to analyze.
  1470.  * \return          Zero if \p value is zero, otherwise all-bits-one.
  1471.  */
  1472. static unsigned all_or_nothing_int( unsigned value )
  1473. {
  1474.     /* MSVC has a warning about unary minus on unsigned, but this is
  1475.      * well-defined and precisely what we want to do here */
  1476. #if defined(_MSC_VER)
  1477. #pragma warning( push )
  1478. #pragma warning( disable : 4146 )
  1479. #endif
  1480.     return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
  1481. #if defined(_MSC_VER)
  1482. #pragma warning( pop )
  1483. #endif
  1484. }
  1485.  
  1486. /** Check whether a size is out of bounds, without branches.
  1487.  *
  1488.  * This is equivalent to `size > max`, but is likely to be compiled to
  1489.  * to code using bitwise operation rather than a branch.
  1490.  *
  1491.  * \param size      Size to check.
  1492.  * \param max       Maximum desired value for \p size.
  1493.  * \return          \c 0 if `size <= max`.
  1494.  * \return          \c 1 if `size > max`.
  1495.  */
  1496. static unsigned size_greater_than( size_t size, size_t max )
  1497. {
  1498.     /* Return the sign bit (1 for negative) of (max - size). */
  1499.     return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) );
  1500. }
  1501.  
  1502. /** Choose between two integer values, without branches.
  1503.  *
  1504.  * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled
  1505.  * to code using bitwise operation rather than a branch.
  1506.  *
  1507.  * \param cond      Condition to test.
  1508.  * \param if1       Value to use if \p cond is nonzero.
  1509.  * \param if0       Value to use if \p cond is zero.
  1510.  * \return          \c if1 if \p cond is nonzero, otherwise \c if0.
  1511.  */
  1512. static unsigned if_int( unsigned cond, unsigned if1, unsigned if0 )
  1513. {
  1514.     unsigned mask = all_or_nothing_int( cond );
  1515.     return( ( mask & if1 ) | (~mask & if0 ) );
  1516. }
  1517.  
  1518. /** Shift some data towards the left inside a buffer without leaking
  1519.  * the length of the data through side channels.
  1520.  *
  1521.  * `mem_move_to_left(start, total, offset)` is functionally equivalent to
  1522.  * ```
  1523.  * memmove(start, start + offset, total - offset);
  1524.  * memset(start + offset, 0, total - offset);
  1525.  * ```
  1526.  * but it strives to use a memory access pattern (and thus total timing)
  1527.  * that does not depend on \p offset. This timing independence comes at
  1528.  * the expense of performance.
  1529.  *
  1530.  * \param start     Pointer to the start of the buffer.
  1531.  * \param total     Total size of the buffer.
  1532.  * \param offset    Offset from which to copy \p total - \p offset bytes.
  1533.  */
  1534. static void mem_move_to_left( void *start,
  1535.                               size_t total,
  1536.                               size_t offset )
  1537. {
  1538.     volatile unsigned char *buf = start;
  1539.     size_t i, n;
  1540.     if( total == 0 )
  1541.         return;
  1542.     for( i = 0; i < total; i++ )
  1543.     {
  1544.         unsigned no_op = size_greater_than( total - offset, i );
  1545.         /* The first `total - offset` passes are a no-op. The last
  1546.          * `offset` passes shift the data one byte to the left and
  1547.          * zero out the last byte. */
  1548.         for( n = 0; n < total - 1; n++ )
  1549.         {
  1550.             unsigned char current = buf[n];
  1551.             unsigned char next = buf[n+1];
  1552.             buf[n] = if_int( no_op, current, next );
  1553.         }
  1554.         buf[total-1] = if_int( no_op, buf[total-1], 0 );
  1555.     }
  1556. }
  1557.  
  1558. /*
  1559.  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
  1560.  */
  1561. int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
  1562.                                  int (*f_rng)(void *, unsigned char *, size_t),
  1563.                                  void *p_rng,
  1564.                                  int mode, size_t *olen,
  1565.                                  const unsigned char *input,
  1566.                                  unsigned char *output,
  1567.                                  size_t output_max_len )
  1568. {
  1569.     int ret;
  1570.     size_t ilen, i, plaintext_max_size;
  1571.     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1572.     /* The following variables take sensitive values: their value must
  1573.      * not leak into the observable behavior of the function other than
  1574.      * the designated outputs (output, olen, return value). Otherwise
  1575.      * this would open the execution of the function to
  1576.      * side-channel-based variants of the Bleichenbacher padding oracle
  1577.      * attack. Potential side channels include overall timing, memory
  1578.      * access patterns (especially visible to an adversary who has access
  1579.      * to a shared memory cache), and branches (especially visible to
  1580.      * an adversary who has access to a shared code cache or to a shared
  1581.      * branch predictor). */
  1582.     size_t pad_count = 0;
  1583.     unsigned bad = 0;
  1584.     unsigned char pad_done = 0;
  1585.     size_t plaintext_size = 0;
  1586.     unsigned output_too_large;
  1587.  
  1588.     RSA_VALIDATE_RET( ctx != NULL );
  1589.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1590.                       mode == MBEDTLS_RSA_PUBLIC );
  1591.     RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1592.     RSA_VALIDATE_RET( input != NULL );
  1593.     RSA_VALIDATE_RET( olen != NULL );
  1594.  
  1595.     ilen = ctx->len;
  1596.     plaintext_max_size = ( output_max_len > ilen - 11 ?
  1597.                            ilen - 11 :
  1598.                            output_max_len );
  1599.  
  1600.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  1601.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1602.  
  1603.     if( ilen < 16 || ilen > sizeof( buf ) )
  1604.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1605.  
  1606.     ret = ( mode == MBEDTLS_RSA_PUBLIC )
  1607.           ? mbedtls_rsa_public(  ctx, input, buf )
  1608.           : mbedtls_rsa_private( ctx, f_rng, p_rng, input, buf );
  1609.  
  1610.     if( ret != 0 )
  1611.         goto cleanup;
  1612.  
  1613.     /* Check and get padding length in constant time and constant
  1614.      * memory trace. The first byte must be 0. */
  1615.     bad |= buf[0];
  1616.  
  1617.     if( mode == MBEDTLS_RSA_PRIVATE )
  1618.     {
  1619.         /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  1620.          * where PS must be at least 8 nonzero bytes. */
  1621.         bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
  1622.  
  1623.         /* Read the whole buffer. Set pad_done to nonzero if we find
  1624.          * the 0x00 byte and remember the padding length in pad_count. */
  1625.         for( i = 2; i < ilen; i++ )
  1626.         {
  1627.             pad_done  |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
  1628.             pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  1629.         }
  1630.     }
  1631.     else
  1632.     {
  1633.         /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
  1634.          * where PS must be at least 8 bytes with the value 0xFF. */
  1635.         bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
  1636.  
  1637.         /* Read the whole buffer. Set pad_done to nonzero if we find
  1638.          * the 0x00 byte and remember the padding length in pad_count.
  1639.          * If there's a non-0xff byte in the padding, the padding is bad. */
  1640.         for( i = 2; i < ilen; i++ )
  1641.         {
  1642.             pad_done |= if_int( buf[i], 0, 1 );
  1643.             pad_count += if_int( pad_done, 0, 1 );
  1644.             bad |= if_int( pad_done, 0, buf[i] ^ 0xFF );
  1645.         }
  1646.     }
  1647.  
  1648.     /* If pad_done is still zero, there's no data, only unfinished padding. */
  1649.     bad |= if_int( pad_done, 0, 1 );
  1650.  
  1651.     /* There must be at least 8 bytes of padding. */
  1652.     bad |= size_greater_than( 8, pad_count );
  1653.  
  1654.     /* If the padding is valid, set plaintext_size to the number of
  1655.      * remaining bytes after stripping the padding. If the padding
  1656.      * is invalid, avoid leaking this fact through the size of the
  1657.      * output: use the maximum message size that fits in the output
  1658.      * buffer. Do it without branches to avoid leaking the padding
  1659.      * validity through timing. RSA keys are small enough that all the
  1660.      * size_t values involved fit in unsigned int. */
  1661.     plaintext_size = if_int( bad,
  1662.                              (unsigned) plaintext_max_size,
  1663.                              (unsigned) ( ilen - pad_count - 3 ) );
  1664.  
  1665.     /* Set output_too_large to 0 if the plaintext fits in the output
  1666.      * buffer and to 1 otherwise. */
  1667.     output_too_large = size_greater_than( plaintext_size,
  1668.                                           plaintext_max_size );
  1669.  
  1670.     /* Set ret without branches to avoid timing attacks. Return:
  1671.      * - INVALID_PADDING if the padding is bad (bad != 0).
  1672.      * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  1673.      *   plaintext does not fit in the output buffer.
  1674.      * - 0 if the padding is correct. */
  1675.     ret = - (int) if_int( bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
  1676.                   if_int( output_too_large, - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
  1677.                           0 ) );
  1678.  
  1679.     /* If the padding is bad or the plaintext is too large, zero the
  1680.      * data that we're about to copy to the output buffer.
  1681.      * We need to copy the same amount of data
  1682.      * from the same buffer whether the padding is good or not to
  1683.      * avoid leaking the padding validity through overall timing or
  1684.      * through memory or cache access patterns. */
  1685.     bad = all_or_nothing_int( bad | output_too_large );
  1686.     for( i = 11; i < ilen; i++ )
  1687.         buf[i] &= ~bad;
  1688.  
  1689.     /* If the plaintext is too large, truncate it to the buffer size.
  1690.      * Copy anyway to avoid revealing the length through timing, because
  1691.      * revealing the length is as bad as revealing the padding validity
  1692.      * for a Bleichenbacher attack. */
  1693.     plaintext_size = if_int( output_too_large,
  1694.                              (unsigned) plaintext_max_size,
  1695.                              (unsigned) plaintext_size );
  1696.  
  1697.     /* Move the plaintext to the leftmost position where it can start in
  1698.      * the working buffer, i.e. make it start plaintext_max_size from
  1699.      * the end of the buffer. Do this with a memory access trace that
  1700.      * does not depend on the plaintext size. After this move, the
  1701.      * starting location of the plaintext is no longer sensitive
  1702.      * information. */
  1703.     mem_move_to_left( buf + ilen - plaintext_max_size,
  1704.                       plaintext_max_size,
  1705.                       plaintext_max_size - plaintext_size );
  1706.  
  1707.     /* Finally copy the decrypted plaintext plus trailing zeros
  1708.      * into the output buffer. */
  1709.     memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
  1710.  
  1711.     /* Report the amount of data we copied to the output buffer. In case
  1712.      * of errors (bad padding or output too large), the value of *olen
  1713.      * when this function returns is not specified. Making it equivalent
  1714.      * to the good case limits the risks of leaking the padding validity. */
  1715.     *olen = plaintext_size;
  1716.  
  1717. cleanup:
  1718.     mbedtls_platform_zeroize( buf, sizeof( buf ) );
  1719.  
  1720.     return( ret );
  1721. }
  1722. #endif /* MBEDTLS_PKCS1_V15 */
  1723.  
  1724. /*
  1725.  * Do an RSA operation, then remove the message padding
  1726.  */
  1727. int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
  1728.                        int (*f_rng)(void *, unsigned char *, size_t),
  1729.                        void *p_rng,
  1730.                        int mode, size_t *olen,
  1731.                        const unsigned char *input,
  1732.                        unsigned char *output,
  1733.                        size_t output_max_len)
  1734. {
  1735.     RSA_VALIDATE_RET( ctx != NULL );
  1736.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1737.                       mode == MBEDTLS_RSA_PUBLIC );
  1738.     RSA_VALIDATE_RET( output_max_len == 0 || output != NULL );
  1739.     RSA_VALIDATE_RET( input != NULL );
  1740.     RSA_VALIDATE_RET( olen != NULL );
  1741.  
  1742.     switch( ctx->padding )
  1743.     {
  1744. #if defined(MBEDTLS_PKCS1_V15)
  1745.         case MBEDTLS_RSA_PKCS_V15:
  1746.             return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, mode, olen,
  1747.                                                 input, output, output_max_len );
  1748. #endif
  1749.  
  1750. #if defined(MBEDTLS_PKCS1_V21)
  1751.         case MBEDTLS_RSA_PKCS_V21:
  1752.             return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, mode, NULL, 0,
  1753.                                            olen, input, output,
  1754.                                            output_max_len );
  1755. #endif
  1756.  
  1757.         default:
  1758.             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  1759.     }
  1760. }
  1761.  
  1762. #if defined(MBEDTLS_PKCS1_V21)
  1763. /*
  1764.  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
  1765.  */
  1766. int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
  1767.                          int (*f_rng)(void *, unsigned char *, size_t),
  1768.                          void *p_rng,
  1769.                          int mode,
  1770.                          mbedtls_md_type_t md_alg,
  1771.                          unsigned int hashlen,
  1772.                          const unsigned char *hash,
  1773.                          unsigned char *sig )
  1774. {
  1775.     size_t olen;
  1776.     unsigned char *p = sig;
  1777.     unsigned char salt[MBEDTLS_MD_MAX_SIZE];
  1778.     size_t slen, min_slen, hlen, offset = 0;
  1779.     int ret;
  1780.     size_t msb;
  1781.     const mbedtls_md_info_t *md_info;
  1782.     mbedtls_md_context_t md_ctx;
  1783.     RSA_VALIDATE_RET( ctx != NULL );
  1784.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  1785.                       mode == MBEDTLS_RSA_PUBLIC );
  1786.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  1787.                         hashlen == 0 ) ||
  1788.                       hash != NULL );
  1789.     RSA_VALIDATE_RET( sig != NULL );
  1790.  
  1791.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  1792.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1793.  
  1794.     if( f_rng == NULL )
  1795.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1796.  
  1797.     olen = ctx->len;
  1798.  
  1799.     if( md_alg != MBEDTLS_MD_NONE )
  1800.     {
  1801.         /* Gather length of hash to sign */
  1802.         md_info = mbedtls_md_info_from_type( md_alg );
  1803.         if( md_info == NULL )
  1804.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1805.  
  1806.         hashlen = mbedtls_md_get_size( md_info );
  1807.     }
  1808.  
  1809.     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
  1810.     if( md_info == NULL )
  1811.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1812.  
  1813.     hlen = mbedtls_md_get_size( md_info );
  1814.  
  1815.     /* Calculate the largest possible salt length. Normally this is the hash
  1816.      * length, which is the maximum length the salt can have. If there is not
  1817.      * enough room, use the maximum salt length that fits. The constraint is
  1818.      * that the hash length plus the salt length plus 2 bytes must be at most
  1819.      * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
  1820.      * (PKCS#1 v2.2) §9.1.1 step 3. */
  1821.     min_slen = hlen - 2;
  1822.     if( olen < hlen + min_slen + 2 )
  1823.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1824.     else if( olen >= hlen + hlen + 2 )
  1825.         slen = hlen;
  1826.     else
  1827.         slen = olen - hlen - 2;
  1828.  
  1829.     memset( sig, 0, olen );
  1830.  
  1831.     /* Generate salt of length slen */
  1832.     if( ( ret = f_rng( p_rng, salt, slen ) ) != 0 )
  1833.         return( MBEDTLS_ERR_RSA_RNG_FAILED + ret );
  1834.  
  1835.     /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
  1836.     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  1837.     p += olen - hlen - slen - 2;
  1838.     *p++ = 0x01;
  1839.     memcpy( p, salt, slen );
  1840.     p += slen;
  1841.  
  1842.     mbedtls_md_init( &md_ctx );
  1843.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  1844.         goto exit;
  1845.  
  1846.     /* Generate H = Hash( M' ) */
  1847.     if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )
  1848.         goto exit;
  1849.     if( ( ret = mbedtls_md_update( &md_ctx, p, 8 ) ) != 0 )
  1850.         goto exit;
  1851.     if( ( ret = mbedtls_md_update( &md_ctx, hash, hashlen ) ) != 0 )
  1852.         goto exit;
  1853.     if( ( ret = mbedtls_md_update( &md_ctx, salt, slen ) ) != 0 )
  1854.         goto exit;
  1855.     if( ( ret = mbedtls_md_finish( &md_ctx, p ) ) != 0 )
  1856.         goto exit;
  1857.  
  1858.     /* Compensate for boundary condition when applying mask */
  1859.     if( msb % 8 == 0 )
  1860.         offset = 1;
  1861.  
  1862.     /* maskedDB: Apply dbMask to DB */
  1863.     if( ( ret = mgf_mask( sig + offset, olen - hlen - 1 - offset, p, hlen,
  1864.                           &md_ctx ) ) != 0 )
  1865.         goto exit;
  1866.  
  1867.     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  1868.     sig[0] &= 0xFF >> ( olen * 8 - msb );
  1869.  
  1870.     p += hlen;
  1871.     *p++ = 0xBC;
  1872.  
  1873.     mbedtls_platform_zeroize( salt, sizeof( salt ) );
  1874.  
  1875. exit:
  1876.     mbedtls_md_free( &md_ctx );
  1877.  
  1878.     if( ret != 0 )
  1879.         return( ret );
  1880.  
  1881.     return( ( mode == MBEDTLS_RSA_PUBLIC )
  1882.             ? mbedtls_rsa_public(  ctx, sig, sig )
  1883.             : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig ) );
  1884. }
  1885. #endif /* MBEDTLS_PKCS1_V21 */
  1886.  
  1887. #if defined(MBEDTLS_PKCS1_V15)
  1888. /*
  1889.  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
  1890.  */
  1891.  
  1892. /* Construct a PKCS v1.5 encoding of a hashed message
  1893.  *
  1894.  * This is used both for signature generation and verification.
  1895.  *
  1896.  * Parameters:
  1897.  * - md_alg:  Identifies the hash algorithm used to generate the given hash;
  1898.  *            MBEDTLS_MD_NONE if raw data is signed.
  1899.  * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.
  1900.  * - hash:    Buffer containing the hashed message or the raw data.
  1901.  * - dst_len: Length of the encoded message.
  1902.  * - dst:     Buffer to hold the encoded message.
  1903.  *
  1904.  * Assumptions:
  1905.  * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.
  1906.  * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.
  1907.  * - dst points to a buffer of size at least dst_len.
  1908.  *
  1909.  */
  1910. static int rsa_rsassa_pkcs1_v15_encode( mbedtls_md_type_t md_alg,
  1911.                                         unsigned int hashlen,
  1912.                                         const unsigned char *hash,
  1913.                                         size_t dst_len,
  1914.                                         unsigned char *dst )
  1915. {
  1916.     size_t oid_size  = 0;
  1917.     size_t nb_pad    = dst_len;
  1918.     unsigned char *p = dst;
  1919.     const char *oid  = NULL;
  1920.  
  1921.     /* Are we signing hashed or raw data? */
  1922.     if( md_alg != MBEDTLS_MD_NONE )
  1923.     {
  1924.         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
  1925.         if( md_info == NULL )
  1926.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1927.  
  1928.         if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
  1929.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1930.  
  1931.         hashlen = mbedtls_md_get_size( md_info );
  1932.  
  1933.         /* Double-check that 8 + hashlen + oid_size can be used as a
  1934.          * 1-byte ASN.1 length encoding and that there's no overflow. */
  1935.         if( 8 + hashlen + oid_size  >= 0x80         ||
  1936.             10 + hashlen            <  hashlen      ||
  1937.             10 + hashlen + oid_size <  10 + hashlen )
  1938.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1939.  
  1940.         /*
  1941.          * Static bounds check:
  1942.          * - Need 10 bytes for five tag-length pairs.
  1943.          *   (Insist on 1-byte length encodings to protect against variants of
  1944.          *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
  1945.          * - Need hashlen bytes for hash
  1946.          * - Need oid_size bytes for hash alg OID.
  1947.          */
  1948.         if( nb_pad < 10 + hashlen + oid_size )
  1949.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1950.         nb_pad -= 10 + hashlen + oid_size;
  1951.     }
  1952.     else
  1953.     {
  1954.         if( nb_pad < hashlen )
  1955.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1956.  
  1957.         nb_pad -= hashlen;
  1958.     }
  1959.  
  1960.     /* Need space for signature header and padding delimiter (3 bytes),
  1961.      * and 8 bytes for the minimal padding */
  1962.     if( nb_pad < 3 + 8 )
  1963.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  1964.     nb_pad -= 3;
  1965.  
  1966.     /* Now nb_pad is the amount of memory to be filled
  1967.      * with padding, and at least 8 bytes long. */
  1968.  
  1969.     /* Write signature header and padding */
  1970.     *p++ = 0;
  1971.     *p++ = MBEDTLS_RSA_SIGN;
  1972.     memset( p, 0xFF, nb_pad );
  1973.     p += nb_pad;
  1974.     *p++ = 0;
  1975.  
  1976.     /* Are we signing raw data? */
  1977.     if( md_alg == MBEDTLS_MD_NONE )
  1978.     {
  1979.         memcpy( p, hash, hashlen );
  1980.         return( 0 );
  1981.     }
  1982.  
  1983.     /* Signing hashed data, add corresponding ASN.1 structure
  1984.      *
  1985.      * DigestInfo ::= SEQUENCE {
  1986.      *   digestAlgorithm DigestAlgorithmIdentifier,
  1987.      *   digest Digest }
  1988.      * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  1989.      * Digest ::= OCTET STRING
  1990.      *
  1991.      * Schematic:
  1992.      * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
  1993.      *                                 TAG-NULL + LEN [ NULL ] ]
  1994.      *                 TAG-OCTET + LEN [ HASH ] ]
  1995.      */
  1996.     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1997.     *p++ = (unsigned char)( 0x08 + oid_size + hashlen );
  1998.     *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1999.     *p++ = (unsigned char)( 0x04 + oid_size );
  2000.     *p++ = MBEDTLS_ASN1_OID;
  2001.     *p++ = (unsigned char) oid_size;
  2002.     memcpy( p, oid, oid_size );
  2003.     p += oid_size;
  2004.     *p++ = MBEDTLS_ASN1_NULL;
  2005.     *p++ = 0x00;
  2006.     *p++ = MBEDTLS_ASN1_OCTET_STRING;
  2007.     *p++ = (unsigned char) hashlen;
  2008.     memcpy( p, hash, hashlen );
  2009.     p += hashlen;
  2010.  
  2011.     /* Just a sanity-check, should be automatic
  2012.      * after the initial bounds check. */
  2013.     if( p != dst + dst_len )
  2014.     {
  2015.         mbedtls_platform_zeroize( dst, dst_len );
  2016.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2017.     }
  2018.  
  2019.     return( 0 );
  2020. }
  2021.  
  2022. /*
  2023.  * Do an RSA operation to sign the message digest
  2024.  */
  2025. int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
  2026.                                int (*f_rng)(void *, unsigned char *, size_t),
  2027.                                void *p_rng,
  2028.                                int mode,
  2029.                                mbedtls_md_type_t md_alg,
  2030.                                unsigned int hashlen,
  2031.                                const unsigned char *hash,
  2032.                                unsigned char *sig )
  2033. {
  2034.     int ret;
  2035.     unsigned char *sig_try = NULL, *verif = NULL;
  2036.  
  2037.     RSA_VALIDATE_RET( ctx != NULL );
  2038.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2039.                       mode == MBEDTLS_RSA_PUBLIC );
  2040.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2041.                         hashlen == 0 ) ||
  2042.                       hash != NULL );
  2043.     RSA_VALIDATE_RET( sig != NULL );
  2044.  
  2045.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  2046.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2047.  
  2048.     /*
  2049.      * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
  2050.      */
  2051.  
  2052.     if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash,
  2053.                                              ctx->len, sig ) ) != 0 )
  2054.         return( ret );
  2055.  
  2056.     /*
  2057.      * Call respective RSA primitive
  2058.      */
  2059.  
  2060.     if( mode == MBEDTLS_RSA_PUBLIC )
  2061.     {
  2062.         /* Skip verification on a public key operation */
  2063.         return( mbedtls_rsa_public( ctx, sig, sig ) );
  2064.     }
  2065.  
  2066.     /* Private key operation
  2067.      *
  2068.      * In order to prevent Lenstra's attack, make the signature in a
  2069.      * temporary buffer and check it before returning it.
  2070.      */
  2071.  
  2072.     sig_try = mbedtls_calloc( 1, ctx->len );
  2073.     if( sig_try == NULL )
  2074.         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  2075.  
  2076.     verif = mbedtls_calloc( 1, ctx->len );
  2077.     if( verif == NULL )
  2078.     {
  2079.         mbedtls_free( sig_try );
  2080.         return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
  2081.     }
  2082.  
  2083.     MBEDTLS_MPI_CHK( mbedtls_rsa_private( ctx, f_rng, p_rng, sig, sig_try ) );
  2084.     MBEDTLS_MPI_CHK( mbedtls_rsa_public( ctx, sig_try, verif ) );
  2085.  
  2086.     if( mbedtls_safer_memcmp( verif, sig, ctx->len ) != 0 )
  2087.     {
  2088.         ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
  2089.         goto cleanup;
  2090.     }
  2091.  
  2092.     memcpy( sig, sig_try, ctx->len );
  2093.  
  2094. cleanup:
  2095.     mbedtls_free( sig_try );
  2096.     mbedtls_free( verif );
  2097.  
  2098.     return( ret );
  2099. }
  2100. #endif /* MBEDTLS_PKCS1_V15 */
  2101.  
  2102. /*
  2103.  * Do an RSA operation to sign the message digest
  2104.  */
  2105. int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
  2106.                     int (*f_rng)(void *, unsigned char *, size_t),
  2107.                     void *p_rng,
  2108.                     int mode,
  2109.                     mbedtls_md_type_t md_alg,
  2110.                     unsigned int hashlen,
  2111.                     const unsigned char *hash,
  2112.                     unsigned char *sig )
  2113. {
  2114.     RSA_VALIDATE_RET( ctx != NULL );
  2115.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2116.                       mode == MBEDTLS_RSA_PUBLIC );
  2117.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2118.                         hashlen == 0 ) ||
  2119.                       hash != NULL );
  2120.     RSA_VALIDATE_RET( sig != NULL );
  2121.  
  2122.     switch( ctx->padding )
  2123.     {
  2124. #if defined(MBEDTLS_PKCS1_V15)
  2125.         case MBEDTLS_RSA_PKCS_V15:
  2126.             return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, mode, md_alg,
  2127.                                               hashlen, hash, sig );
  2128. #endif
  2129.  
  2130. #if defined(MBEDTLS_PKCS1_V21)
  2131.         case MBEDTLS_RSA_PKCS_V21:
  2132.             return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, mode, md_alg,
  2133.                                         hashlen, hash, sig );
  2134. #endif
  2135.  
  2136.         default:
  2137.             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  2138.     }
  2139. }
  2140.  
  2141. #if defined(MBEDTLS_PKCS1_V21)
  2142. /*
  2143.  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2144.  */
  2145. int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
  2146.                                int (*f_rng)(void *, unsigned char *, size_t),
  2147.                                void *p_rng,
  2148.                                int mode,
  2149.                                mbedtls_md_type_t md_alg,
  2150.                                unsigned int hashlen,
  2151.                                const unsigned char *hash,
  2152.                                mbedtls_md_type_t mgf1_hash_id,
  2153.                                int expected_salt_len,
  2154.                                const unsigned char *sig )
  2155. {
  2156.     int ret;
  2157.     size_t siglen;
  2158.     unsigned char *p;
  2159.     unsigned char *hash_start;
  2160.     unsigned char result[MBEDTLS_MD_MAX_SIZE];
  2161.     unsigned char zeros[8];
  2162.     unsigned int hlen;
  2163.     size_t observed_salt_len, msb;
  2164.     const mbedtls_md_info_t *md_info;
  2165.     mbedtls_md_context_t md_ctx;
  2166.     unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  2167.  
  2168.     RSA_VALIDATE_RET( ctx != NULL );
  2169.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2170.                       mode == MBEDTLS_RSA_PUBLIC );
  2171.     RSA_VALIDATE_RET( sig != NULL );
  2172.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2173.                         hashlen == 0 ) ||
  2174.                       hash != NULL );
  2175.  
  2176.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V21 )
  2177.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2178.  
  2179.     siglen = ctx->len;
  2180.  
  2181.     if( siglen < 16 || siglen > sizeof( buf ) )
  2182.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2183.  
  2184.     ret = ( mode == MBEDTLS_RSA_PUBLIC )
  2185.           ? mbedtls_rsa_public(  ctx, sig, buf )
  2186.           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, buf );
  2187.  
  2188.     if( ret != 0 )
  2189.         return( ret );
  2190.  
  2191.     p = buf;
  2192.  
  2193.     if( buf[siglen - 1] != 0xBC )
  2194.         return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  2195.  
  2196.     if( md_alg != MBEDTLS_MD_NONE )
  2197.     {
  2198.         /* Gather length of hash to sign */
  2199.         md_info = mbedtls_md_info_from_type( md_alg );
  2200.         if( md_info == NULL )
  2201.             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2202.  
  2203.         hashlen = mbedtls_md_get_size( md_info );
  2204.     }
  2205.  
  2206.     md_info = mbedtls_md_info_from_type( mgf1_hash_id );
  2207.     if( md_info == NULL )
  2208.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2209.  
  2210.     hlen = mbedtls_md_get_size( md_info );
  2211.  
  2212.     memset( zeros, 0, 8 );
  2213.  
  2214.     /*
  2215.      * Note: EMSA-PSS verification is over the length of N - 1 bits
  2216.      */
  2217.     msb = mbedtls_mpi_bitlen( &ctx->N ) - 1;
  2218.  
  2219.     if( buf[0] >> ( 8 - siglen * 8 + msb ) )
  2220.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2221.  
  2222.     /* Compensate for boundary condition when applying mask */
  2223.     if( msb % 8 == 0 )
  2224.     {
  2225.         p++;
  2226.         siglen -= 1;
  2227.     }
  2228.  
  2229.     if( siglen < hlen + 2 )
  2230.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2231.     hash_start = p + siglen - hlen - 1;
  2232.  
  2233.     mbedtls_md_init( &md_ctx );
  2234.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
  2235.         goto exit;
  2236.  
  2237.     ret = mgf_mask( p, siglen - hlen - 1, hash_start, hlen, &md_ctx );
  2238.     if( ret != 0 )
  2239.         goto exit;
  2240.  
  2241.     buf[0] &= 0xFF >> ( siglen * 8 - msb );
  2242.  
  2243.     while( p < hash_start - 1 && *p == 0 )
  2244.         p++;
  2245.  
  2246.     if( *p++ != 0x01 )
  2247.     {
  2248.         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  2249.         goto exit;
  2250.     }
  2251.  
  2252.     observed_salt_len = hash_start - p;
  2253.  
  2254.     if( expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
  2255.         observed_salt_len != (size_t) expected_salt_len )
  2256.     {
  2257.         ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  2258.         goto exit;
  2259.     }
  2260.  
  2261.     /*
  2262.      * Generate H = Hash( M' )
  2263.      */
  2264.     ret = mbedtls_md_starts( &md_ctx );
  2265.     if ( ret != 0 )
  2266.         goto exit;
  2267.     ret = mbedtls_md_update( &md_ctx, zeros, 8 );
  2268.     if ( ret != 0 )
  2269.         goto exit;
  2270.     ret = mbedtls_md_update( &md_ctx, hash, hashlen );
  2271.     if ( ret != 0 )
  2272.         goto exit;
  2273.     ret = mbedtls_md_update( &md_ctx, p, observed_salt_len );
  2274.     if ( ret != 0 )
  2275.         goto exit;
  2276.     ret = mbedtls_md_finish( &md_ctx, result );
  2277.     if ( ret != 0 )
  2278.         goto exit;
  2279.  
  2280.     if( memcmp( hash_start, result, hlen ) != 0 )
  2281.     {
  2282.         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2283.         goto exit;
  2284.     }
  2285.  
  2286. exit:
  2287.     mbedtls_md_free( &md_ctx );
  2288.  
  2289.     return( ret );
  2290. }
  2291.  
  2292. /*
  2293.  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2294.  */
  2295. int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
  2296.                            int (*f_rng)(void *, unsigned char *, size_t),
  2297.                            void *p_rng,
  2298.                            int mode,
  2299.                            mbedtls_md_type_t md_alg,
  2300.                            unsigned int hashlen,
  2301.                            const unsigned char *hash,
  2302.                            const unsigned char *sig )
  2303. {
  2304.     mbedtls_md_type_t mgf1_hash_id;
  2305.     RSA_VALIDATE_RET( ctx != NULL );
  2306.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2307.                       mode == MBEDTLS_RSA_PUBLIC );
  2308.     RSA_VALIDATE_RET( sig != NULL );
  2309.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2310.                         hashlen == 0 ) ||
  2311.                       hash != NULL );
  2312.  
  2313.     mgf1_hash_id = ( ctx->hash_id != MBEDTLS_MD_NONE )
  2314.                              ? (mbedtls_md_type_t) ctx->hash_id
  2315.                              : md_alg;
  2316.  
  2317.     return( mbedtls_rsa_rsassa_pss_verify_ext( ctx, f_rng, p_rng, mode,
  2318.                                        md_alg, hashlen, hash,
  2319.                                        mgf1_hash_id, MBEDTLS_RSA_SALT_LEN_ANY,
  2320.                                        sig ) );
  2321.  
  2322. }
  2323. #endif /* MBEDTLS_PKCS1_V21 */
  2324.  
  2325. #if defined(MBEDTLS_PKCS1_V15)
  2326. /*
  2327.  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
  2328.  */
  2329. int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
  2330.                                  int (*f_rng)(void *, unsigned char *, size_t),
  2331.                                  void *p_rng,
  2332.                                  int mode,
  2333.                                  mbedtls_md_type_t md_alg,
  2334.                                  unsigned int hashlen,
  2335.                                  const unsigned char *hash,
  2336.                                  const unsigned char *sig )
  2337. {
  2338.     int ret = 0;
  2339.     size_t sig_len;
  2340.     unsigned char *encoded = NULL, *encoded_expected = NULL;
  2341.  
  2342.     RSA_VALIDATE_RET( ctx != NULL );
  2343.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2344.                       mode == MBEDTLS_RSA_PUBLIC );
  2345.     RSA_VALIDATE_RET( sig != NULL );
  2346.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2347.                         hashlen == 0 ) ||
  2348.                       hash != NULL );
  2349.  
  2350.     sig_len = ctx->len;
  2351.  
  2352.     if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
  2353.         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
  2354.  
  2355.     /*
  2356.      * Prepare expected PKCS1 v1.5 encoding of hash.
  2357.      */
  2358.  
  2359.     if( ( encoded          = mbedtls_calloc( 1, sig_len ) ) == NULL ||
  2360.         ( encoded_expected = mbedtls_calloc( 1, sig_len ) ) == NULL )
  2361.     {
  2362.         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2363.         goto cleanup;
  2364.     }
  2365.  
  2366.     if( ( ret = rsa_rsassa_pkcs1_v15_encode( md_alg, hashlen, hash, sig_len,
  2367.                                              encoded_expected ) ) != 0 )
  2368.         goto cleanup;
  2369.  
  2370.     /*
  2371.      * Apply RSA primitive to get what should be PKCS1 encoded hash.
  2372.      */
  2373.  
  2374.     ret = ( mode == MBEDTLS_RSA_PUBLIC )
  2375.           ? mbedtls_rsa_public(  ctx, sig, encoded )
  2376.           : mbedtls_rsa_private( ctx, f_rng, p_rng, sig, encoded );
  2377.     if( ret != 0 )
  2378.         goto cleanup;
  2379.  
  2380.     /*
  2381.      * Compare
  2382.      */
  2383.  
  2384.     if( ( ret = mbedtls_safer_memcmp( encoded, encoded_expected,
  2385.                                       sig_len ) ) != 0 )
  2386.     {
  2387.         ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2388.         goto cleanup;
  2389.     }
  2390.  
  2391. cleanup:
  2392.  
  2393.     if( encoded != NULL )
  2394.     {
  2395.         mbedtls_platform_zeroize( encoded, sig_len );
  2396.         mbedtls_free( encoded );
  2397.     }
  2398.  
  2399.     if( encoded_expected != NULL )
  2400.     {
  2401.         mbedtls_platform_zeroize( encoded_expected, sig_len );
  2402.         mbedtls_free( encoded_expected );
  2403.     }
  2404.  
  2405.     return( ret );
  2406. }
  2407. #endif /* MBEDTLS_PKCS1_V15 */
  2408.  
  2409. /*
  2410.  * Do an RSA operation and check the message digest
  2411.  */
  2412. int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
  2413.                       int (*f_rng)(void *, unsigned char *, size_t),
  2414.                       void *p_rng,
  2415.                       int mode,
  2416.                       mbedtls_md_type_t md_alg,
  2417.                       unsigned int hashlen,
  2418.                       const unsigned char *hash,
  2419.                       const unsigned char *sig )
  2420. {
  2421.     RSA_VALIDATE_RET( ctx != NULL );
  2422.     RSA_VALIDATE_RET( mode == MBEDTLS_RSA_PRIVATE ||
  2423.                       mode == MBEDTLS_RSA_PUBLIC );
  2424.     RSA_VALIDATE_RET( sig != NULL );
  2425.     RSA_VALIDATE_RET( ( md_alg  == MBEDTLS_MD_NONE &&
  2426.                         hashlen == 0 ) ||
  2427.                       hash != NULL );
  2428.  
  2429.     switch( ctx->padding )
  2430.     {
  2431. #if defined(MBEDTLS_PKCS1_V15)
  2432.         case MBEDTLS_RSA_PKCS_V15:
  2433.             return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, f_rng, p_rng, mode, md_alg,
  2434.                                                 hashlen, hash, sig );
  2435. #endif
  2436.  
  2437. #if defined(MBEDTLS_PKCS1_V21)
  2438.         case MBEDTLS_RSA_PKCS_V21:
  2439.             return mbedtls_rsa_rsassa_pss_verify( ctx, f_rng, p_rng, mode, md_alg,
  2440.                                           hashlen, hash, sig );
  2441. #endif
  2442.  
  2443.         default:
  2444.             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
  2445.     }
  2446. }
  2447.  
  2448. /*
  2449.  * Copy the components of an RSA key
  2450.  */
  2451. int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
  2452. {
  2453.     int ret;
  2454.     RSA_VALIDATE_RET( dst != NULL );
  2455.     RSA_VALIDATE_RET( src != NULL );
  2456.  
  2457.     dst->ver = src->ver;
  2458.     dst->len = src->len;
  2459.  
  2460.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->N, &src->N ) );
  2461.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->E, &src->E ) );
  2462.  
  2463.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->D, &src->D ) );
  2464.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->P, &src->P ) );
  2465.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Q, &src->Q ) );
  2466.  
  2467. #if !defined(MBEDTLS_RSA_NO_CRT)
  2468.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DP, &src->DP ) );
  2469.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->DQ, &src->DQ ) );
  2470.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->QP, &src->QP ) );
  2471.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RP, &src->RP ) );
  2472.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RQ, &src->RQ ) );
  2473. #endif
  2474.  
  2475.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->RN, &src->RN ) );
  2476.  
  2477.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vi, &src->Vi ) );
  2478.     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->Vf, &src->Vf ) );
  2479.  
  2480.     dst->padding = src->padding;
  2481.     dst->hash_id = src->hash_id;
  2482.  
  2483. cleanup:
  2484.     if( ret != 0 )
  2485.         mbedtls_rsa_free( dst );
  2486.  
  2487.     return( ret );
  2488. }
  2489.  
  2490. /*
  2491.  * Free the components of an RSA key
  2492.  */
  2493. void mbedtls_rsa_free( mbedtls_rsa_context *ctx )
  2494. {
  2495.     if( ctx == NULL )
  2496.         return;
  2497.  
  2498.     mbedtls_mpi_free( &ctx->Vi );
  2499.     mbedtls_mpi_free( &ctx->Vf );
  2500.     mbedtls_mpi_free( &ctx->RN );
  2501.     mbedtls_mpi_free( &ctx->D  );
  2502.     mbedtls_mpi_free( &ctx->Q  );
  2503.     mbedtls_mpi_free( &ctx->P  );
  2504.     mbedtls_mpi_free( &ctx->E  );
  2505.     mbedtls_mpi_free( &ctx->N  );
  2506.  
  2507. #if !defined(MBEDTLS_RSA_NO_CRT)
  2508.     mbedtls_mpi_free( &ctx->RQ );
  2509.     mbedtls_mpi_free( &ctx->RP );
  2510.     mbedtls_mpi_free( &ctx->QP );
  2511.     mbedtls_mpi_free( &ctx->DQ );
  2512.     mbedtls_mpi_free( &ctx->DP );
  2513. #endif /* MBEDTLS_RSA_NO_CRT */
  2514.  
  2515. #if defined(MBEDTLS_THREADING_C)
  2516.     mbedtls_mutex_free( &ctx->mutex );
  2517. #endif
  2518. }
  2519.  
  2520. #endif /* !MBEDTLS_RSA_ALT */
  2521.  
  2522. #if defined(MBEDTLS_SELF_TEST)
  2523.  
  2524. #include "mbedtls/sha1.h"
  2525.  
  2526. /*
  2527.  * Example RSA-1024 keypair, for test purposes
  2528.  */
  2529. #define KEY_LEN 128
  2530.  
  2531. #define RSA_N   "9292758453063D803DD603D5E777D788" \
  2532.                 "8ED1D5BF35786190FA2F23EBC0848AEA" \
  2533.                 "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
  2534.                 "7130B9CED7ACDF54CFC7555AC14EEBAB" \
  2535.                 "93A89813FBF3C4F8066D2D800F7C38A8" \
  2536.                 "1AE31942917403FF4946B0A83D3D3E05" \
  2537.                 "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
  2538.                 "5E94BB77B07507233A0BC7BAC8F90F79"
  2539.  
  2540. #define RSA_E   "10001"
  2541.  
  2542. #define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
  2543.                 "66CA472BC44D253102F8B4A9D3BFA750" \
  2544.                 "91386C0077937FE33FA3252D28855837" \
  2545.                 "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
  2546.                 "DF79C5CE07EE72C7F123142198164234" \
  2547.                 "CABB724CF78B8173B9F880FC86322407" \
  2548.                 "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
  2549.                 "071513A1E85B5DFA031F21ECAE91A34D"
  2550.  
  2551. #define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
  2552.                 "2C01CAD19EA484A87EA4377637E75500" \
  2553.                 "FCB2005C5C7DD6EC4AC023CDA285D796" \
  2554.                 "C3D9E75E1EFC42488BB4F1D13AC30A57"
  2555.  
  2556. #define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
  2557.                 "E211C2B9E5DB1ED0BF61D0D9899620F4" \
  2558.                 "910E4168387E3C30AA1E00C339A79508" \
  2559.                 "8452DD96A9A5EA5D9DCA68DA636032AF"
  2560.  
  2561. #define PT_LEN  24
  2562. #define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
  2563.                 "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
  2564.  
  2565. #if defined(MBEDTLS_PKCS1_V15)
  2566. static int myrand( void *rng_state, unsigned char *output, size_t len )
  2567. {
  2568. #if !defined(__OpenBSD__)
  2569.     size_t i;
  2570.  
  2571.     if( rng_state != NULL )
  2572.         rng_state  = NULL;
  2573.  
  2574.     for( i = 0; i < len; ++i )
  2575.         output[i] = rand();
  2576. #else
  2577.     if( rng_state != NULL )
  2578.         rng_state = NULL;
  2579.  
  2580.     arc4random_buf( output, len );
  2581. #endif /* !OpenBSD */
  2582.  
  2583.     return( 0 );
  2584. }
  2585. #endif /* MBEDTLS_PKCS1_V15 */
  2586.  
  2587. /*
  2588.  * Checkup routine
  2589.  */
  2590. int mbedtls_rsa_self_test( int verbose )
  2591. {
  2592.     int ret = 0;
  2593. #if defined(MBEDTLS_PKCS1_V15)
  2594.     size_t len;
  2595.     mbedtls_rsa_context rsa;
  2596.     unsigned char rsa_plaintext[PT_LEN];
  2597.     unsigned char rsa_decrypted[PT_LEN];
  2598.     unsigned char rsa_ciphertext[KEY_LEN];
  2599. #if defined(MBEDTLS_SHA1_C)
  2600.     unsigned char sha1sum[20];
  2601. #endif
  2602.  
  2603.     mbedtls_mpi K;
  2604.  
  2605.     mbedtls_mpi_init( &K );
  2606.     mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
  2607.  
  2608.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_N  ) );
  2609.     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, &K, NULL, NULL, NULL, NULL ) );
  2610.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_P  ) );
  2611.     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, &K, NULL, NULL, NULL ) );
  2612.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_Q  ) );
  2613.     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, &K, NULL, NULL ) );
  2614.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_D  ) );
  2615.     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, &K, NULL ) );
  2616.     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &K, 16, RSA_E  ) );
  2617.     MBEDTLS_MPI_CHK( mbedtls_rsa_import( &rsa, NULL, NULL, NULL, NULL, &K ) );
  2618.  
  2619.     MBEDTLS_MPI_CHK( mbedtls_rsa_complete( &rsa ) );
  2620.  
  2621.     if( verbose != 0 )
  2622.         mbedtls_printf( "  RSA key validation: " );
  2623.  
  2624.     if( mbedtls_rsa_check_pubkey(  &rsa ) != 0 ||
  2625.         mbedtls_rsa_check_privkey( &rsa ) != 0 )
  2626.     {
  2627.         if( verbose != 0 )
  2628.             mbedtls_printf( "failed\n" );
  2629.  
  2630.         ret = 1;
  2631.         goto cleanup;
  2632.     }
  2633.  
  2634.     if( verbose != 0 )
  2635.         mbedtls_printf( "passed\n  PKCS#1 encryption : " );
  2636.  
  2637.     memcpy( rsa_plaintext, RSA_PT, PT_LEN );
  2638.  
  2639.     if( mbedtls_rsa_pkcs1_encrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PUBLIC,
  2640.                                    PT_LEN, rsa_plaintext,
  2641.                                    rsa_ciphertext ) != 0 )
  2642.     {
  2643.         if( verbose != 0 )
  2644.             mbedtls_printf( "failed\n" );
  2645.  
  2646.         ret = 1;
  2647.         goto cleanup;
  2648.     }
  2649.  
  2650.     if( verbose != 0 )
  2651.         mbedtls_printf( "passed\n  PKCS#1 decryption : " );
  2652.  
  2653.     if( mbedtls_rsa_pkcs1_decrypt( &rsa, myrand, NULL, MBEDTLS_RSA_PRIVATE,
  2654.                                    &len, rsa_ciphertext, rsa_decrypted,
  2655.                                    sizeof(rsa_decrypted) ) != 0 )
  2656.     {
  2657.         if( verbose != 0 )
  2658.             mbedtls_printf( "failed\n" );
  2659.  
  2660.         ret = 1;
  2661.         goto cleanup;
  2662.     }
  2663.  
  2664.     if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
  2665.     {
  2666.         if( verbose != 0 )
  2667.             mbedtls_printf( "failed\n" );
  2668.  
  2669.         ret = 1;
  2670.         goto cleanup;
  2671.     }
  2672.  
  2673.     if( verbose != 0 )
  2674.         mbedtls_printf( "passed\n" );
  2675.  
  2676. #if defined(MBEDTLS_SHA1_C)
  2677.     if( verbose != 0 )
  2678.         mbedtls_printf( "  PKCS#1 data sign  : " );
  2679.  
  2680.     if( mbedtls_sha1_ret( rsa_plaintext, PT_LEN, sha1sum ) != 0 )
  2681.     {
  2682.         if( verbose != 0 )
  2683.             mbedtls_printf( "failed\n" );
  2684.  
  2685.         return( 1 );
  2686.     }
  2687.  
  2688.     if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL,
  2689.                                 MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 0,
  2690.                                 sha1sum, rsa_ciphertext ) != 0 )
  2691.     {
  2692.         if( verbose != 0 )
  2693.             mbedtls_printf( "failed\n" );
  2694.  
  2695.         ret = 1;
  2696.         goto cleanup;
  2697.     }
  2698.  
  2699.     if( verbose != 0 )
  2700.         mbedtls_printf( "passed\n  PKCS#1 sig. verify: " );
  2701.  
  2702.     if( mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL,
  2703.                                   MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 0,
  2704.                                   sha1sum, rsa_ciphertext ) != 0 )
  2705.     {
  2706.         if( verbose != 0 )
  2707.             mbedtls_printf( "failed\n" );
  2708.  
  2709.         ret = 1;
  2710.         goto cleanup;
  2711.     }
  2712.  
  2713.     if( verbose != 0 )
  2714.         mbedtls_printf( "passed\n" );
  2715. #endif /* MBEDTLS_SHA1_C */
  2716.  
  2717.     if( verbose != 0 )
  2718.         mbedtls_printf( "\n" );
  2719.  
  2720. cleanup:
  2721.     mbedtls_mpi_free( &K );
  2722.     mbedtls_rsa_free( &rsa );
  2723. #else /* MBEDTLS_PKCS1_V15 */
  2724.     ((void) verbose);
  2725. #endif /* MBEDTLS_PKCS1_V15 */
  2726.     return( ret );
  2727. }
  2728.  
  2729. #endif /* MBEDTLS_SELF_TEST */
  2730.  
  2731. #endif /* MBEDTLS_RSA_C */
  2732.