SHA-256 Explained — How It Works and When to Use It
SHA-256 is a cryptographic hash function that produces a fixed 256-bit fingerprint of any input. Learn how SHA-256 works, why it's secure, how it compares to MD5 and SHA-1, and when to use SHA-256 vs SHA-512.
What is a hash function?
A hash function takes an input of any size and produces a fixed-size output called a digest or hash. The same input always produces the same output, but even a single character change produces a completely different hash — this is called the avalanche effect.
Crucially, hash functions are one-way: you can compute a hash from an input, but you cannot recover the original input from the hash alone.
SHA-256 at a glance
SHA-256 is part of the SHA-2 family, designed by the NSA and published by NIST in 2001. It produces a 256-bit (32-byte) hash, expressed as 64 hexadecimal characters. It processes input in 512-bit blocks and runs 64 rounds of a compression function per block.
SHA-256 vs MD5 vs SHA-1 vs SHA-512
| Algorithm | Output size | Speed | Secure? | Use today? |
|---|---|---|---|---|
| MD5 | 128-bit / 32 hex | Very fast | ✗ Broken | ✗ Not for security |
| SHA-1 | 160-bit / 40 hex | Fast | ✗ Deprecated | ✗ Not for security |
| SHA-256 | 256-bit / 64 hex | Fast | ✓ Secure | ✓ Yes — recommended |
| SHA-512 | 512-bit / 128 hex | Moderate | ✓ Secure | ✓ Yes — when extra margin needed |
Common uses of SHA-256
- File integrity verification — compare hashes before and after download to confirm the file wasn't tampered with
- Password storage — store the hash of a password, never the plaintext (with a salt to prevent rainbow table attacks)
- Digital signatures — TLS/SSL certificates, code signing, and document signing all use SHA-256 internally
- Blockchain — Bitcoin's proof-of-work and transaction IDs are SHA-256 double-hashes
- HMAC authentication — API authentication (JWT, OAuth) uses HMAC-SHA256 to sign tokens
- Content-addressable storage — Git stores every file and commit as a SHA hash
Why is MD5 no longer safe?
MD5 is collision-vulnerable — researchers have demonstrated that two different inputs can produce the same MD5 hash in seconds on consumer hardware. This makes it useless for any security purpose. SHA-1 has similar weaknesses following Google's SHAttered attack in 2017, which produced the first practical SHA-1 collision. SHA-256 has no known practical attacks.
MD5 remains acceptable for non-security checksums (detecting accidental corruption), but never for authentication, signatures, or password hashing.
SHA-256 vs SHA-512 — which is faster?
On 64-bit CPUs, SHA-512 can actually be faster than SHA-256 for large inputs because it processes 1024-bit blocks in fewer rounds. For short inputs (passwords, tokens), SHA-256 is faster. Both are secure — SHA-512 provides a larger security margin but the difference is academic for most applications. Use SHA-256 unless you have a specific reason to need 512-bit output.