From c60e99ff629c384aa7b9ac4f7badcf3cfdf953c1 Mon Sep 17 00:00:00 2001
From: Raymond Mao <raymond.mao@linaro.org>
Date: Thu, 3 Oct 2024 14:50:20 -0700
Subject: [PATCH] mbedtls: Enable smaller implementation for SHA256/512

Smaller implementation for SHA256 and SHA512 helps to reduce the
ROM footprint though it has a certain impact on performance.
As a trade-off, enable it as a default config when MbedTLS is
enabled can reduce the target size significantly with acceptable
performance loss.

Signed-off-by: Raymond Mao <raymond.mao@linaro.org>
Reviewed-by: Ilias Apalodimas <ilias.apalodimas@linaro.org>
---
 lib/mbedtls/Kconfig              | 24 ++++++++++++++++++++++++
 lib/mbedtls/mbedtls_def_config.h |  6 ++++++
 2 files changed, 30 insertions(+)

diff --git a/lib/mbedtls/Kconfig b/lib/mbedtls/Kconfig
index 262abb2cec..8e3a94c6f2 100644
--- a/lib/mbedtls/Kconfig
+++ b/lib/mbedtls/Kconfig
@@ -164,6 +164,18 @@ config SHA256_MBEDTLS
 	  This option enables support of hashing using SHA256 algorithm
 	  with MbedTLS crypto library.
 
+if SHA256_MBEDTLS
+
+config SHA256_SMALLER
+	bool "Enable SHA256 smaller implementation with MbedTLS crypto library"
+	depends on SHA256_MBEDTLS
+	default y if SHA256_MBEDTLS
+	help
+	  This option enables support of hashing using SHA256 algorithm
+	  smaller implementation with MbedTLS crypto library.
+
+endif
+
 config SHA512_MBEDTLS
 	bool "Enable SHA512 support with MbedTLS crypto library"
 	depends on MBEDTLS_LIB_CRYPTO && SHA512
@@ -172,6 +184,18 @@ config SHA512_MBEDTLS
 	  This option enables support of hashing using SHA512 algorithm
 	  with MbedTLS crypto library.
 
+if SHA512_MBEDTLS
+
+config SHA512_SMALLER
+	bool "Enable SHA512 smaller implementation with MbedTLS crypto library"
+	depends on SHA512_MBEDTLS
+	default y if SHA512_MBEDTLS
+	help
+	  This option enables support of hashing using SHA512 algorithm
+	  smaller implementation with MbedTLS crypto library.
+
+endif
+
 config SHA384_MBEDTLS
 	bool "Enable SHA384 support with MbedTLS crypto library"
 	depends on MBEDTLS_LIB_CRYPTO && SHA384
diff --git a/lib/mbedtls/mbedtls_def_config.h b/lib/mbedtls/mbedtls_def_config.h
index 6fba053bd7..1af911c200 100644
--- a/lib/mbedtls/mbedtls_def_config.h
+++ b/lib/mbedtls/mbedtls_def_config.h
@@ -35,6 +35,9 @@
 #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT
 #define MBEDTLS_SHA256_ALT
 #endif
+#if CONFIG_IS_ENABLED(SHA256_SMALLER)
+#define MBEDTLS_SHA256_SMALLER
+#endif
 #endif
 
 #if CONFIG_IS_ENABLED(SHA384)
@@ -48,6 +51,9 @@
 #if defined CONFIG_MBEDTLS_LIB_CRYPTO_ALT
 #define MBEDTLS_SHA512_ALT
 #endif
+#if CONFIG_IS_ENABLED(SHA512_SMALLER)
+#define MBEDTLS_SHA512_SMALLER
+#endif
 #endif
 
 #if defined CONFIG_MBEDTLS_LIB_X509
-- 
2.39.5