Understanding SHA-256: A Deep Dive
Understanding SHA-256: A Deep Dive
March 25, 2025
SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that converts an input (message) into a fixed-length 256-bit (32-byte) hash value. It is part of the SHA-2 family and is widely used in security applications like password hashing, digital signatures, and blockchain.
How SHA-256 Works
SHA-256 follows the Merkle–Damgård construction and consists of several key steps:
1. Preprocessing
a) Message Padding
- The input message is padded so that its length becomes a multiple of 512 bits (64 bytes).
- Padding starts with a single “1” bit, followed by enough “0” bits.
- The last 64 bits store the original message length in bits.
b) Message Chunking
- The padded message is divided into 512-bit blocks.
- Each block is processed independently.
2. Hash Computation
SHA-256 uses a compression function that processes each 512-bit block using 64 rounds of transformations.
a) Initialization
SHA-256 starts with eight 32-bit hash values (H0 to H7), known as initial hash values:
H0 = 6a09e667
H1 = bb67ae85
H2 = 3c6ef372
H3 = a54ff53a
H4 = 510e527f
H5 = 9b05688c
H6 = 1f83d9ab
H7 = 5be0cd19These are fractional parts of the square roots of the first 8 prime numbers.
b) Message Expansion (Schedule)
- Each 512-bit block is expanded into 64 words (W0 to W63), where each word is 32 bits.
- The first 16 words come from the original block.
- The remaining words are generated using bitwise operations.
c) Round Processing
For each of the 64 rounds, the algorithm:
- Uses 8 working variables (A, B, C, D, E, F, G, H).
- Computes two key functions:
- Ch (Choose): Selects bits based on the value of E.
- Maj (Majority): Chooses bits based on a majority vote of A, B, C.
- Uses two bitwise rotation functions (
Σ0andΣ1). - Updates hash values using:
T1 = H + Σ1(E) + Ch(E,F,G) + K[i] + W[i]
T2 = Σ0(A) + Maj(A,B,C)K[i]is a predefined 64-element constant table derived from cube roots of the first 64 prime numbers.
- The working variables are updated:
H = G
G = F
F = E
E = D + T1
D = C
C = B
B = A
A = T1 + T2d) Hash Update
- After processing all 64 rounds, the final values of A, B, C, D, E, F, G, and H are added to the initial hash values.
3. Final Hash Output
- After processing all 512-bit chunks, the final hash is concatenated from H0 to H7.
- The final 256-bit output is represented as 64 hexadecimal characters.
Example: Hashing “hello”
SHA-256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824Properties of SHA-256
- Deterministic: Same input always produces the same output.
- Fixed Length: Always 256 bits, regardless of input size.
- Avalanche Effect: Small changes in input cause large changes in output.
- One-Way Function: Nearly impossible to reverse.
- Collision Resistant: No two different inputs should produce the same hash.