SHA-256 is a cryptographic hash function that produces a fixed-size 256-bit (32-byte) hash. It is deterministic, collision-resistant, and designed for security-critical applications.
!assets/hashing-algorithm-sha256.png
How SHA-256 Works
- Preprocessing:
- Pad the input to a multiple of 512 bits.
- Append a
1
, then addk
zeros, and finally append the original message length (64 bits).
- Initialize Hash Values:
- Use constants derived from the fractional parts of square roots of the first 8 primes (eight 32-bit words).
- Example:
h0 = 0x6a09e667, h1 = 0xbb67ae85, ...
.
- Process Blocks:
- Split the padded message into 512-bit blocks.
- For each block:
- Expand the block into 64 words using a message schedule.
- Perform 64 rounds of compression using bitwise operations (e.g., XOR, AND, modular addition).
- Compression Function A compression function is applied to each block, creating a new hash value. This function involves mixing the bits of the current hash value and the message block.
- Iteration Repeat the compression function for each block, using the output of each iteration as input for the next.
- Final Hash:
- Combine the intermediate hash values to produce the final 256-bit digest.
Example: SHA-256 for String “Hello”
- Input: “Hello” → ASCII
48656C6C6F
. - Padding:
- Length = 40 bits (5 bytes).
- Pad with
1
, 407 zeros, and0000000000000028
(hex for 40 bits).
- Hash Computation:
- After processing, the final hash is:
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
.
- After processing, the final hash is:
Use Cases
SHA-256
- Cryptographic security in:
- Digital signatures (SSL/TLS certificates).
- Password storage (hashed+salted).
- Blockchain (Bitcoin transactions).
- File integrity verification (e.g., software downloads).
- Guarantees: Pre-image resistance, collision resistance.