SHA-256 is a cryptographic hash function that produces a fixed-size 256-bit (32-byte) hash. It is deterministiccollision-resistant, and designed for security-critical applications.

!assets/hashing-algorithm-sha256.png

How SHA-256 Works

  1. Preprocessing:
    • Pad the input to a multiple of 512 bits.
    • Append a 1, then add k zeros, and finally append the original message length (64 bits).
  2. 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, ....
  3. 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).
  4. 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.
  5. Iteration Repeat the compression function for each block, using the output of each iteration as input for the next.
  6. Final Hash:
    • Combine the intermediate hash values to produce the final 256-bit digest.

Example: SHA-256 for String “Hello”

  1. Input: “Hello” → ASCII 48656C6C6F.
  2. Padding:
    • Length = 40 bits (5 bytes).
    • Pad with 1, 407 zeros, and 0000000000000028 (hex for 40 bits).
  3. Hash Computation:
    • After processing, the final hash is: 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969.

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.