Add tests for mbedtls_ctr_increment_counter
Signed-off-by: Dave Rodgman <dave.rodgman@arm.com>
diff --git a/tests/suites/test_suite_ctr_drbg.function b/tests/suites/test_suite_ctr_drbg.function
index 1f0a072..425c43e 100644
--- a/tests/suites/test_suite_ctr_drbg.function
+++ b/tests/suites/test_suite_ctr_drbg.function
@@ -2,6 +2,7 @@
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "string.h"
+#include "ctr.h"
#if defined(MBEDTLS_THREADING_PTHREAD)
#include "mbedtls/threading.h"
@@ -443,3 +444,75 @@
AES_PSA_DONE();
}
/* END_CASE */
+
+/* BEGIN_CASE */
+void ctr_increment_rollover()
+{
+ uint8_t c[16];
+ uint8_t r[16];
+
+ // test all increments from 2^n - 1 to 2^n (i.e. where we roll over into the next bit)
+ for (int n = 0; n <= 128; n++) {
+ memset(c, 0, 16);
+ memset(r, 0, 16);
+
+ // set least significant (highest address) n bits to 1, i.e. generate (2^n - 1)
+ for (int i = 0; i < n; i++) {
+ int bit = i % 8;
+ int byte = (i / 8);
+ c[15 - byte] |= 1 << bit;
+ }
+ // increment to get 2^n
+ mbedtls_ctr_increment_counter(c);
+
+ // now generate a reference result equal to 2^n - i.e. set only bit (n + 1)
+ // if n == 127, this will not set any bits (i.e. wraps to 0).
+ int bit = n % 8;
+ int byte = n / 8;
+ if (byte < 16) {
+ r[15 - byte] = 1 << bit;
+ }
+
+ TEST_MEMORY_COMPARE(c, 16, r, 16);
+ }
+
+ uint64_t lsb = 10, msb = 20;
+ MBEDTLS_PUT_UINT64_BE(msb, c, 0);
+ MBEDTLS_PUT_UINT64_BE(lsb, c, 8);
+ memcpy(r, c, 16);
+ mbedtls_ctr_increment_counter(c);
+ for (int i = 15; i >= 0; i--) {
+ r[i] += 1;
+ if (r[i] != 0) {
+ break;
+ }
+ }
+ TEST_MEMORY_COMPARE(c, 16, r, 16);
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void ctr_increment(data_t *x)
+{
+ uint8_t c[16];
+ uint8_t r[16];
+
+ // initialise c and r from test argument
+ memset(c, 0, 16);
+ memcpy(c, x->x, x->len);
+ memcpy(r, c, 16);
+
+ // increment c
+ mbedtls_ctr_increment_counter(c);
+ // increment reference
+ for (int i = 15; i >= 0; i--) {
+ r[i] += 1;
+ if (r[i] != 0) {
+ break;
+ }
+ }
+
+ // test that mbedtls_ctr_increment_counter behaviour matches reference
+ TEST_MEMORY_COMPARE(c, 16, r, 16);
+}
+/* END_CASE */