sha256: fix undefined behavior in left shift of BYTE by 24#40
Open
MayCXC wants to merge 1 commit intoB-Con:masterfrom
Open
sha256: fix undefined behavior in left shift of BYTE by 24#40MayCXC wants to merge 1 commit intoB-Con:masterfrom
MayCXC wants to merge 1 commit intoB-Con:masterfrom
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
In
sha256_transform, the expressiondata[j] << 24promotes theBYTE(unsigned char) operand toint(signed 32-bit) before shifting. Whendata[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:
Fix: cast each
BYTEtoWORD(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).