Skip to content

sha256: fix undefined behavior in left shift of BYTE by 24#40

Open
MayCXC wants to merge 1 commit intoB-Con:masterfrom
MayCXC:fix/sha256-ubsan
Open

sha256: fix undefined behavior in left shift of BYTE by 24#40
MayCXC wants to merge 1 commit intoB-Con:masterfrom
MayCXC:fix/sha256-ubsan

Conversation

@MayCXC
Copy link

@MayCXC MayCXC commented Mar 18, 2026

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 (C11 6.5.7p4).

Found by UndefinedBehaviorSanitizer:

sha256.c:49:19: runtime error: left shift of 128 by 24 places
cannot be represented in type 'int'

Fix: cast each BYTE to WORD (unsigned int) before shifting. This ensures the shift operates on unsigned 32-bit values, which is well-defined for all byte values.

The fix is a single line change with no behavioral difference for correct inputs (the UB happened to produce the correct result on all common platforms, but relying on UB is not portable).

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant