From 591ff05384f36658022f3c67f408dbc903ec8897 Mon Sep 17 00:00:00 2001 From: Dave Rodgman Date: Sat, 13 Jan 2024 16:42:38 +0000 Subject: [PATCH] Use optimised counter increment in AES-CTR and CTR-DRBG Signed-off-by: Dave Rodgman --- library/aes.c | 7 ++----- library/ctr_drbg.c | 17 +++++------------ 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/library/aes.c b/library/aes.c index ced8a32639..b1a5c3ed10 100644 --- a/library/aes.c +++ b/library/aes.c @@ -53,6 +53,7 @@ #endif #include "mbedtls/platform.h" +#include "ctr.h" /* * This is a convenience shorthand macro to check if we need reverse S-box and @@ -1456,11 +1457,7 @@ int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx, if (ret != 0) { goto exit; } - for (int j = 16; j > 0; j--) { - if (++nonce_counter[j - 1] != 0) { - break; - } - } + mbedtls_ctr_increment_counter(nonce_counter); } else { n -= offset; } diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c index da34f950b8..f3995f709c 100644 --- a/library/ctr_drbg.c +++ b/library/ctr_drbg.c @@ -14,6 +14,7 @@ #if defined(MBEDTLS_CTR_DRBG_C) +#include "ctr.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" @@ -333,7 +334,7 @@ static int ctr_drbg_update_internal(mbedtls_ctr_drbg_context *ctx, { unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN]; unsigned char *p = tmp; - int i, j; + int j; int ret = 0; #if !defined(MBEDTLS_AES_C) psa_status_t status; @@ -346,11 +347,7 @@ static int ctr_drbg_update_internal(mbedtls_ctr_drbg_context *ctx, /* * Increase counter */ - for (i = MBEDTLS_CTR_DRBG_BLOCKSIZE; i > 0; i--) { - if (++ctx->counter[i - 1] != 0) { - break; - } - } + mbedtls_ctr_increment_counter(ctx->counter); /* * Crypt counter block @@ -652,13 +649,9 @@ int mbedtls_ctr_drbg_random_with_add(void *p_rng, while (output_len > 0) { /* - * Increase counter + * Increase counter (treat it as a 128-bit big-endian integer). */ - for (i = MBEDTLS_CTR_DRBG_BLOCKSIZE; i > 0; i--) { - if (++ctx->counter[i - 1] != 0) { - break; - } - } + mbedtls_ctr_increment_counter(ctx->counter); /* * Crypt counter block