libmbedtls: add interfaces in mbedtls for context memory operation

For integrating into OPTEE_OS, it needs add some interfaces:
1. add mbedtls_cipher_clone() for cipher to copy context between two
operations.
2. add mbedtls_cipher_setup_info() for cipher. cipher need to get its
"cipher_info" according the key length, while the key length is not an
input in allocate function. So, use a default key len in the beginning.
It need to reset the cipher info again in init function.
3. add mbedtls_cipher_cmac_setup() for cmac. This function is separate
from mbedtls_cipher_cmac_starts().
4. copy hmac context in md.

Acked-by: Etienne Carriere <etienne.carriere@linaro.org>
Signed-off-by: Edison Ai <edison.ai@arm.com>
Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
[jf: rebase onto mbedtls-2.22.0]
[jf: rebase onto mbedtls-2.27.0]
Signed-off-by: Jerome Forissier <jerome@forissier.org>
[jf: rebase onto mbedtls-2.28.1, fix typo in comment]
Signed-off-by: Jerome Forissier <jerome.forissier@linaro.org>
[jw: rebase onto mbedtls-3.4.0, adjust new coding style]
Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
[tve: rebase onto mbedtls-3.6.0, adjust for changes between 3.4 and 3.6]
Signed-off-by: Tom Van Eyck <tom.vaneyck@kuleuven.be>
diff --git a/lib/libmbedtls/mbedtls/library/cmac.c b/lib/libmbedtls/mbedtls/library/cmac.c
index eda10d0..a1ef947 100644
--- a/lib/libmbedtls/mbedtls/library/cmac.c
+++ b/lib/libmbedtls/mbedtls/library/cmac.c
@@ -153,11 +153,26 @@
     }
 }
 
+int mbedtls_cipher_cmac_setup(mbedtls_cipher_context_t *ctx)
+{
+    mbedtls_cmac_context_t *cmac_ctx;
+
+    /* Allocated and initialise in the cipher context memory for the CMAC
+     * context */
+    cmac_ctx = mbedtls_calloc(1, sizeof(mbedtls_cmac_context_t));
+    if (cmac_ctx == NULL)
+        return MBEDTLS_ERR_CIPHER_ALLOC_FAILED;
+
+    ctx->cmac_ctx = cmac_ctx;
+
+    mbedtls_platform_zeroize(cmac_ctx->state, sizeof(cmac_ctx->state));
+    return 0;
+}
+
 int mbedtls_cipher_cmac_starts(mbedtls_cipher_context_t *ctx,
                                const unsigned char *key, size_t keybits)
 {
     mbedtls_cipher_type_t type;
-    mbedtls_cmac_context_t *cmac_ctx;
     int retval;
 
     if (ctx == NULL || ctx->cipher_info == NULL || key == NULL) {
@@ -181,18 +196,11 @@
             return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
     }
 
-    /* Allocated and initialise in the cipher context memory for the CMAC
-     * context */
-    cmac_ctx = mbedtls_calloc(1, sizeof(mbedtls_cmac_context_t));
-    if (cmac_ctx == NULL) {
-        return MBEDTLS_ERR_CIPHER_ALLOC_FAILED;
-    }
+    /* Check if cmac ctx had been allocated by mbedtls_cipher_cmac_setup() */
+    if( ctx->cmac_ctx != NULL )
+        return 0;
 
-    ctx->cmac_ctx = cmac_ctx;
-
-    mbedtls_platform_zeroize(cmac_ctx->state, sizeof(cmac_ctx->state));
-
-    return 0;
+    return mbedtls_cipher_cmac_setup( ctx );
 }
 
 int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,