Handle encryption with private key and decryption with public key as per RFC 2313

(cherry picked from commit e6ee41f932)
This commit is contained in:
Paul Bakker 2013-01-16 13:26:56 +01:00
parent c048493374
commit 5f5593a30e
2 changed files with 52 additions and 17 deletions

View file

@ -16,6 +16,8 @@ Bugfix
Pégourié-Gonnard) Pégourié-Gonnard)
* Added max length check for rsa_pkcs1_sign with PKCS#1 v2.1 * Added max length check for rsa_pkcs1_sign with PKCS#1 v2.1
* Memory leak when using RSA_PKCS_V21 operations fixed * Memory leak when using RSA_PKCS_V21 operations fixed
* Handle encryption with private key and decryption with public key as per
RFC 2313
Security Security
* Fixed potential memory zeroization on miscrafted RSA key (found by Eloi * Fixed potential memory zeroization on miscrafted RSA key (found by Eloi

View file

@ -386,6 +386,8 @@ int rsa_pkcs1_encrypt( rsa_context *ctx,
nb_pad = olen - 3 - ilen; nb_pad = olen - 3 - ilen;
*p++ = 0; *p++ = 0;
if( mode == RSA_PUBLIC )
{
*p++ = RSA_CRYPT; *p++ = RSA_CRYPT;
while( nb_pad-- > 0 ) while( nb_pad-- > 0 )
@ -403,6 +405,15 @@ int rsa_pkcs1_encrypt( rsa_context *ctx,
p++; p++;
} }
}
else
{
*p++ = RSA_SIGN;
while( nb_pad-- > 0 )
*p++ = 0xFF;
}
*p++ = 0; *p++ = 0;
memcpy( p, input, ilen ); memcpy( p, input, ilen );
break; break;
@ -476,6 +487,7 @@ int rsa_pkcs1_decrypt( rsa_context *ctx,
int ret; int ret;
size_t ilen; size_t ilen;
unsigned char *p; unsigned char *p;
unsigned char bt;
unsigned char buf[1024]; unsigned char buf[1024];
#if defined(POLARSSL_PKCS1_V21) #if defined(POLARSSL_PKCS1_V21)
unsigned char lhash[POLARSSL_MD_MAX_SIZE]; unsigned char lhash[POLARSSL_MD_MAX_SIZE];
@ -502,16 +514,37 @@ int rsa_pkcs1_decrypt( rsa_context *ctx,
{ {
case RSA_PKCS_V15: case RSA_PKCS_V15:
if( *p++ != 0 || *p++ != RSA_CRYPT ) if( *p++ != 0 )
return( POLARSSL_ERR_RSA_INVALID_PADDING ); return( POLARSSL_ERR_RSA_INVALID_PADDING );
while( *p != 0 ) bt = *p++;
if( ( bt != RSA_CRYPT && mode == RSA_PRIVATE ) ||
( bt != RSA_SIGN && mode == RSA_PUBLIC ) )
{ {
if( p >= buf + ilen - 1 )
return( POLARSSL_ERR_RSA_INVALID_PADDING ); return( POLARSSL_ERR_RSA_INVALID_PADDING );
}
if( bt == RSA_CRYPT )
{
while( *p != 0 && p < buf + ilen - 1 )
p++;
if( *p != 0 || p >= buf + ilen - 1 )
return( POLARSSL_ERR_RSA_INVALID_PADDING );
p++; p++;
} }
else
{
while( *p == 0xFF && p < buf + ilen - 1 )
p++; p++;
if( *p != 0 || p >= buf + ilen - 1 )
return( POLARSSL_ERR_RSA_INVALID_PADDING );
p++;
}
break; break;
#if defined(POLARSSL_PKCS1_V21) #if defined(POLARSSL_PKCS1_V21)