MD5与SHA256填充步骤是否一致?C语言实现问题咨询
Troubleshooting SHA256 Padding Issue (vs Working MD5 Implementation)
Hey there! Let's break down why your MD5 works but SHA256 is misbehaving—your hunch about padding differences is spot-on. Here's the key breakdown and fix:
Core Differences Between MD5 and SHA256 Padding
Both algorithms follow a similar initial padding pattern, but the length field at the end is drastically different:
- Shared Step: First append a single
0x80byte (binary10000000) to the input message, then fill with0x00bytes until the total length is aligned for the final block. Both use 512-bit (64-byte) blocks. - Critical Difference: Length Field
- MD5: Adds an 8-byte (64-bit) little-endian value representing the original message length in bits.
- SHA256: Adds a 16-byte (128-bit) big-endian value representing the original message length in bits.
Your "toto" Test Case Analysis
For the input "toto" (4 bytes = 32 bits):
- MD5 Padding (Correct):
You appended 1 byte0x80, 51 bytes0x00, then the 8-byte little-endian length (0x20 0x00 0x00 0x00 0x00 0x00 0x00 0x00). This totals 64 bytes, which fits MD5's requirements perfectly—hence your working result. - SHA256 Padding (Incorrect):
You reused the exact same padding as MD5, which means:- You only added an 8-byte length field instead of the required 16 bytes.
- The length field is in little-endian instead of big-endian.
This throws off the entire block structure SHA256 expects, leading to your invalid hash result.
Fix Steps
- Adjust Padding Calculation:
For SHA256, after adding0x80, fill with0x00bytes until the total length is 64 bytes minus 16 bytes (to leave space for the 128-bit length field). For"toto", that means 43 bytes of0x00(4 original + 10x80+ 430x00= 48 bytes; 48 + 16 = 64). - Implement the 128-bit Big-Endian Length Field:
For 32 bits of input length, the SHA256 length field is 12 bytes of0x00followed by 4 bytes0x00 0x00 0x00 0x20(big-endian representation of 32). - Validate the Correct Hash:
The standard SHA256 hash for"toto"isc7911af3adbd12a035b289556d96470a75d486555177e0e2e67d71f7a0a26660—your corrected implementation should match this.
内容的提问来源于stack exchange,提问作者Hugo Eynard
相关产品推荐
相关产品推荐

