You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 0x80 byte (binary 10000000) to the input message, then fill with 0x00 bytes 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 byte 0x80, 51 bytes 0x00, 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:
    1. You only added an 8-byte length field instead of the required 16 bytes.
    2. 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

  1. Adjust Padding Calculation:
    For SHA256, after adding 0x80, fill with 0x00 bytes 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 of 0x00 (4 original + 1 0x80 + 43 0x00 = 48 bytes; 48 + 16 = 64).
  2. Implement the 128-bit Big-Endian Length Field:
    For 32 bits of input length, the SHA256 length field is 12 bytes of 0x00 followed by 4 bytes 0x00 0x00 0x00 0x20 (big-endian representation of 32).
  3. Validate the Correct Hash:
    The standard SHA256 hash for "toto" is c7911af3adbd12a035b289556d96470a75d486555177e0e2e67d71f7a0a26660—your corrected implementation should match this.

内容的提问来源于stack exchange,提问作者Hugo Eynard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:28:20