From 94f48e00523ad931f9db4a34b02b92c28298101f Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Thu, 5 Sep 2019 13:02:57 +0100 Subject: [PATCH] MD: Use no-op for context SHA-256 init() and free() When MBEDTLS_MD_SINGLE_HASH is set, the underlying digest's context is embedded into mbedtls_md_context_t, which is zeroized before the underlying digest's init() function is called. For those digests where initialization is zeroization, the init() call can therefore be omitted. Similarly, when free()-ing an mbedtls_md_context_t, the entire context is zeroized in the end, hence if the underlying digest's free() function is zeroization, it can be omitted. --- include/mbedtls/md_internal.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/include/mbedtls/md_internal.h b/include/mbedtls/md_internal.h index 2cd518577..d44c8af73 100644 --- a/include/mbedtls/md_internal.h +++ b/include/mbedtls/md_internal.h @@ -79,9 +79,21 @@ extern "C" { //#define MBEDTLS_MD_INFO_SHA256 /* SHA-256 */ +static inline void mbedtls_md_sha256_init_free_dummy( void* ctx ) +{ + /* Zero-initialization can be skipped. */ + ((void) ctx); +} #define MBEDTLS_MD_INFO_SHA256_TYPE MBEDTLS_MD_SHA256 #define MBEDTLS_MD_INFO_SHA256_CTX_TYPE mbedtls_sha256_context +#if defined(MBEDTLS_MD_SINGLE_HASH) +/* mbedtls_md_sha256_init() only zeroizes, which is redundant + * because mbedtls_md_context is zeroized in mbedtls_md_init(), + * and the mbedtls_sha256_context is embedded in mbedtls_md_context_t. */ +#define MBEDTLS_MD_INFO_SHA256_INIT_FUNC mbedtls_md_sha256_init_free_dummy +#else #define MBEDTLS_MD_INFO_SHA256_INIT_FUNC mbedtls_sha256_init +#endif /* MBEDTLS_MD_SINGLE_HASH */ #define MBEDTLS_MD_INFO_SHA256_NAME "SHA256" #define MBEDTLS_MD_INFO_SHA256_SIZE 32 #define MBEDTLS_MD_INFO_SHA256_BLOCKSIZE 64 @@ -90,7 +102,14 @@ extern "C" { #define MBEDTLS_MD_INFO_SHA256_FINISH_FUNC mbedtls_sha224_finish_wrap #define MBEDTLS_MD_INFO_SHA256_DIGEST_FUNC mbedtls_sha256_wrap #define MBEDTLS_MD_INFO_SHA256_ALLOC_FUNC mbedtls_sha224_ctx_alloc +#if defined(MBEDTLS_MD_SINGLE_HASH) +/* mbedtls_md_sha256_free() only zeroizes, which is redundant + * because mbedtls_md_context is zeroized in mbedtls_md_init(), + * and the mbedtls_sha256_context is embedded in mbedtls_md_context_t. */ +#define MBEDTLS_MD_INFO_SHA256_FREE_FUNC mbedtls_md_sha256_init_free_dummy +#else #define MBEDTLS_MD_INFO_SHA256_FREE_FUNC mbedtls_sha224_ctx_free +#endif /* MBEDTLS_MD_SINGLE_HASH */ #define MBEDTLS_MD_INFO_SHA256_CLONE_FUNC mbedtls_sha224_clone_wrap #define MBEDTLS_MD_INFO_SHA256_PROCESS_FUNC mbedtls_sha224_process_wrap