diff --git a/library/pkcs7.c b/library/pkcs7.c
index 8c2a3ecaf3..1c73709de3 100644
--- a/library/pkcs7.c
+++ b/library/pkcs7.c
@@ -523,8 +523,12 @@ int mbedtls_pkcs7_signed_data_verify( mbedtls_pkcs7 *pkcs7,
         return( MBEDTLS_ERR_PKCS7_ALLOC_FAILED );
     }
 
-    mbedtls_md( md_info, data, datalen, hash );
-
+    ret = mbedtls_md( md_info, data, datalen, hash );
+    if( ret != 0 )
+    {
+        mbedtls_free( hash );
+        return( ret );
+    }
     ret = mbedtls_pk_verify( &pk_cxt, md_alg, hash, 0,
                                       pkcs7->signed_data.signers.sig.p,
                                       pkcs7->signed_data.signers.sig.len );
diff --git a/tests/suites/test_suite_pkcs7.function b/tests/suites/test_suite_pkcs7.function
index d85a455613..e2d76f36a9 100644
--- a/tests/suites/test_suite_pkcs7.function
+++ b/tests/suites/test_suite_pkcs7.function
@@ -285,9 +285,10 @@ void pkcs7_verify_hash( char *pkcs7_file, char *crt, char *filetobesigned )
 
     md_info = mbedtls_md_info_from_type( md_alg );
 
-    mbedtls_md( md_info, data, datalen, hash );
+    res = mbedtls_md( md_info, data, datalen, hash );
+    TEST_ASSERT( res == 0 );
 
-    res = mbedtls_pkcs7_signed_hash_verify( &pkcs7, &x509, hash, sizeof(hash));
+    res = mbedtls_pkcs7_signed_hash_verify( &pkcs7, &x509, hash, sizeof(hash) );
     TEST_ASSERT( res == 0 );
 
 exit: