From 6fec4fc527e6d7a8246715c9c552a610bcb4c386 Mon Sep 17 00:00:00 2001 From: Aaron Paterson Date: Tue, 17 Mar 2026 23:48:03 -0600 Subject: [PATCH] sha256: cast BYTE to WORD before left shift to avoid undefined behavior In sha256_transform, the expression `data[j] << 24` promotes the BYTE (unsigned char) operand to int (signed 32-bit) before shifting. When data[j] >= 128, shifting by 24 produces a value that cannot be represented in a signed 32-bit int, which is undefined behavior per the C standard. Found by UndefinedBehaviorSanitizer: sha256.c:49:19: runtime error: left shift of 128 by 24 places cannot be represented in type 'int' Fix: explicitly cast each BYTE to WORD (unsigned int) before shifting. This ensures the shift operates on unsigned 32-bit values throughout. --- sha256.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sha256.c b/sha256.c index eb9c5c0..29b81ee 100644 --- a/sha256.c +++ b/sha256.c @@ -46,7 +46,7 @@ void sha256_transform(SHA256_CTX *ctx, const BYTE data[]) WORD a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; for (i = 0, j = 0; i < 16; ++i, j += 4) - m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); + m[i] = ((WORD)data[j] << 24) | ((WORD)data[j + 1] << 16) | ((WORD)data[j + 2] << 8) | ((WORD)data[j + 3]); for ( ; i < 64; ++i) m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];