From 4e8e044070ed60f721a20d399a6bf888ff1bbc5e Mon Sep 17 00:00:00 2001 From: Steffen Jaeckel Date: Tue, 14 Apr 2026 08:45:14 +0200 Subject: [PATCH] Introduce `LTC_ALIGNED_BUF_SIZE()`. Since there's absolutely no way to ensure that a struct is somehow aligned -- all those compile-time mechanism are best-effort and no guarantee -- we align the necessary buffers at run-time. AES-NI already introduced that, let's improve a bit upon its usage. Signed-off-by: Steffen Jaeckel --- src/headers/tomcrypt_cipher.h | 2 +- src/headers/tomcrypt_macros.h | 5 +++++ src/headers/tomcrypt_private.h | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/headers/tomcrypt_cipher.h b/src/headers/tomcrypt_cipher.h index f2eca0cb..b370fedb 100644 --- a/src/headers/tomcrypt_cipher.h +++ b/src/headers/tomcrypt_cipher.h @@ -35,7 +35,7 @@ struct saferp_key { #ifdef LTC_RIJNDAEL struct rijndael_key { - unsigned char K[(60 + 60 + 4) * sizeof(ulong32)]; + unsigned char K[LTC_ALIGNED_BUF_SIZE(ulong32, 60 + 60, 16)]; ulong32 *eK; ulong32 *dK; int Nr; diff --git a/src/headers/tomcrypt_macros.h b/src/headers/tomcrypt_macros.h index de2b51e1..16e37054 100644 --- a/src/headers/tomcrypt_macros.h +++ b/src/headers/tomcrypt_macros.h @@ -453,6 +453,11 @@ static inline ulong64 ROR64(ulong64 word, int i) #define LTC_UNUSED_PARAM(x) (void)(x) #endif +/* Calculates the number of bytes required to hold a buffer that will later on be + * aligned by using LTC_ALIGN_BUF(). + */ +#define LTC_ALIGNED_BUF_SIZE(type, n, align) (((n) + ((align)/sizeof(type))) * sizeof(type)) + /* there is no snprintf before Visual C++ 2015 */ #if defined(_MSC_VER) && _MSC_VER < 1900 #define snprintf _snprintf diff --git a/src/headers/tomcrypt_private.h b/src/headers/tomcrypt_private.h index 16afb8b9..4de5e5ed 100644 --- a/src/headers/tomcrypt_private.h +++ b/src/headers/tomcrypt_private.h @@ -33,7 +33,7 @@ LTC_STATIC_ASSERT(correct_ltc_uintptr_size, sizeof(ltc_uintptr) == sizeof(void*) /* Aligns a `unsigned char` buffer `buf` to `n` bytes and returns that aligned address. * Make sure that the buffer that is passed is huge enough. */ -#define LTC_ALIGN_BUF(buf, n) ((void*)((ltc_uintptr)&((unsigned char*)(buf))[n - 1] & (~(CONSTPTR(n) - CONSTPTR(1))))) +#define LTC_ALIGN_BUF(buf, align) ((void*)((ltc_uintptr)&((unsigned char*)(buf))[(align) - 1] & (~(CONSTPTR(align) - CONSTPTR(1))))) #define LTC_OID_MAX_STRLEN 256