RSA: Use hashlen as the hash input size as documented
Where hashlen was previously ignored when the hash length could be
inferred from an md_alg parameter, the two must now match.
Adapt the existing tests accordingly. Adapt the sample programs accordingly.
This commit does not add any negative testing.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/rsa.c b/library/rsa.c
index a788337..57b8a6f 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -1799,7 +1799,8 @@
if( md_info == NULL )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
- hashlen = mbedtls_md_get_size( md_info );
+ if( hashlen != mbedtls_md_get_size( md_info ) )
+ return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
}
md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->hash_id );
@@ -1934,14 +1935,13 @@
* Parameters:
* - md_alg: Identifies the hash algorithm used to generate the given hash;
* MBEDTLS_MD_NONE if raw data is signed.
- * - hashlen: Length of hash in case hashlen is MBEDTLS_MD_NONE.
+ * - hashlen: Length of hash. Must match md_alg if that's not NONE.
* - hash: Buffer containing the hashed message or the raw data.
* - dst_len: Length of the encoded message.
* - dst: Buffer to hold the encoded message.
*
* Assumptions:
- * - hash has size hashlen if md_alg == MBEDTLS_MD_NONE.
- * - hash has size corresponding to md_alg if md_alg != MBEDTLS_MD_NONE.
+ * - hash has size hashlen.
* - dst points to a buffer of size at least dst_len.
*
*/
@@ -1966,7 +1966,8 @@
if( mbedtls_oid_get_oid_by_md( md_alg, &oid, &oid_size ) != 0 )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
- hashlen = mbedtls_md_get_size( md_info );
+ if( hashlen != mbedtls_md_get_size( md_info ) )
+ return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
/* Double-check that 8 + hashlen + oid_size can be used as a
* 1-byte ASN.1 length encoding and that there's no overflow. */
@@ -2031,6 +2032,8 @@
* TAG-NULL + LEN [ NULL ] ]
* TAG-OCTET + LEN [ HASH ] ]
*/
+ if( 0x08 + oid_size + hashlen >= 0x80 )
+ return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
*p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
*p++ = (unsigned char)( 0x08 + oid_size + hashlen );
*p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
@@ -2212,7 +2215,8 @@
if( md_info == NULL )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
- hashlen = mbedtls_md_get_size( md_info );
+ if( hashlen != mbedtls_md_get_size( md_info ) )
+ return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
}
md_info = mbedtls_md_info_from_type( mgf1_hash_id );
@@ -2683,7 +2687,7 @@
}
if( mbedtls_rsa_pkcs1_sign( &rsa, myrand, NULL,
- MBEDTLS_MD_SHA1, 0,
+ MBEDTLS_MD_SHA1, 20,
sha1sum, rsa_ciphertext ) != 0 )
{
if( verbose != 0 )
@@ -2696,7 +2700,7 @@
if( verbose != 0 )
mbedtls_printf( "passed\n PKCS#1 sig. verify: " );
- if( mbedtls_rsa_pkcs1_verify( &rsa, MBEDTLS_MD_SHA1, 0,
+ if( mbedtls_rsa_pkcs1_verify( &rsa, MBEDTLS_MD_SHA1, 20,
sha1sum, rsa_ciphertext ) != 0 )
{
if( verbose != 0 )