SHA-256 and Hashing Explained: What Makes Data Tamper-Proof
Hashing is not encryption — and confusing the two causes serious security bugs. Learn how SHA-256, MD5, and bcrypt work, when to use each, and why you should never store plain-text passwords.
Hashing, Encryption and Encoding Are Different Things
A hash function turns input of any size into a fixed-size digest. It has no key and no inverse: you cannot “decrypt” a hash. Encryption is reversible with a key, and its purpose is secrecy. Encoding (Base64, hex, URL encoding) is reversible by anyone and provides no security at all. Mixing these up causes real bugs: storing “encrypted” passwords that the server can decrypt, or treating a Base64 string as if it were protected.
| Hashing | Encryption | Encoding | |
|---|---|---|---|
| Reversible? | No | Yes, with the key | Yes, by anyone |
| Key? | No (HMAC adds one) | Yes | No |
| Output size | Fixed (32 bytes for SHA-256) | ≈ input size | Larger than input |
| Typical use | Integrity, fingerprints, signatures | Confidentiality | Transport through text-only channels |
| Example | SHA-256 | AES-GCM | Base64 |
What SHA-256 Produces
SHA-256 belongs to the SHA-2 family, published by NIST in 2001 and specified today in FIPS 180-4. It processes the input in 512-bit blocks and always outputs 256 bits, usually written as 64 hexadecimal characters. These digests are real and you can reproduce them in the hash generator:
SHA-256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
SHA-256("hello!") = ce06092fb948d9ffac7d1a376e404b26b7575bcc11ee05a4615fef4fec3a308b
SHA-256("Hello") = 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
SHA-256("hello\n") = 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03
SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855One extra character or one changed letter produces an unrelated digest — the avalanche effect. The properties that make a cryptographic hash useful are:
- Deterministic: the same bytes always give the same digest, on any machine.
- Preimage resistance: given a digest, finding any input that produces it is infeasible.
- Second-preimage resistance: given one input, finding a different input with the same digest is infeasible.
- Collision resistance: finding any two inputs with the same digest is infeasible. For a 256-bit hash the generic attack needs about 2¹²⁸ operations.
Preimage resistance does not mean a hash hides its input. If the input comes from a small set — a phone number, a date of birth, a short password — an attacker hashes every candidate and compares. That is why hashing an email address does not anonymise it.
Algorithm Comparison
| Algorithm | Output | Status | Notes |
|---|---|---|---|
| MD5 | 128 bits | Broken | Practical collisions since 2004. Acceptable only as a non-security checksum. |
| SHA-1 | 160 bits | Broken | First public collision (SHAttered) in 2017; chosen-prefix collisions in 2020. Do not use for signatures. |
| SHA-256 | 256 bits | Secure | Default general-purpose choice: checksums, signatures, HMAC, content addressing. |
| SHA-512 | 512 bits | Secure | Same family as SHA-256, larger output; often faster on 64-bit CPUs without SHA hardware instructions. |
| SHA-3 (SHA3-256) | 256 bits | Secure | Different internal design (Keccak), standardised in 2015. Not vulnerable to length extension. |
| bcrypt / scrypt / Argon2id | varies | Passwords | Deliberately slow, salted password hashing. Not general-purpose hashes. |
“Broken” refers to collisions. Nobody can reverse an MD5 digest of a random 32-byte file, so MD5 still detects accidental corruption. It must not be used where an attacker could craft two inputs — certificates, signatures, deduplication of untrusted uploads.
Where You Meet SHA-256 in Practice
- Download checksums. Projects publish a
SHA256SUMSfile; you hash the download and compare. - Subresource Integrity.
<script integrity="sha384-…">makes the browser refuse a CDN file whose hash changed. SRI uses Base64, not hex. - Signatures and certificates. TLS certificates, code signing and JWTs (RS256, ES256) sign a SHA-256 digest of the data.
- Content addressing. Docker image digests (
sha256:…) and cache keys identify content by its hash. Git still defaults to SHA-1 but supports a SHA-256 object format. - HMAC. Webhook signatures and the HS256 JWT algorithm, covered below.
Computing a Hash: Code and Command Line
// Node.js
import crypto from 'node:crypto';
crypto.createHash('sha256').update('hello', 'utf8').digest('hex');
// → '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
crypto.createHash('sha256').update('hello').digest('base64');
// → 'LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=' (same 32 bytes)
// Browser (Web Crypto, async, HTTPS or localhost only)
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode('hello'));
const hex = [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
// Large files: stream instead of reading into memory
import fs from 'node:fs';
const h = crypto.createHash('sha256');
for await (const chunk of fs.createReadStream('big.iso')) h.update(chunk);
h.digest('hex');# Linux # macOS sha256sum file.zip shasum -a 256 file.zip # Windows PowerShell Get-FileHash file.zip -Algorithm SHA256 # prints uppercase hex # Hashing a string: -n matters echo "hello" | sha256sum # 5891b5b5… (includes the newline) echo -n hello | sha256sum # 2cf24dba…
Why Two Hashes of “the Same” Data Don't Match
A digest mismatch almost always means the bytes differ, not that a library is wrong. Check, in order:
- Trailing newline.
echoand many editors add\n; Windows files may end lines with\r\n. - Text encoding. Hash functions take bytes. UTF-8 and UTF-16 encodings of the same string give different digests. Always encode to UTF-8 explicitly.
- Unicode normalisation. “café” with a precomposed é hashes to
850f7dc4…; with e + combining accent it hashes to81ef060b…. Both look identical on screen. - Output format. Hex vs Base64, or uppercase vs lowercase hex. Compare raw bytes, or normalise case first.
- Re-serialised JSON. Parsing and re-stringifying changes whitespace and sometimes key order. Hash the exact bytes you received, not
JSON.stringify(JSON.parse(body)).
Length Extension and Why HMAC Exists
A tempting way to sign a message is SHA-256(secret + message). It is insecure. SHA-256 (like MD5 and SHA-1) exposes its internal state in the digest, so anyone who sees the signature of message can compute a valid signature for message + padding + extra without knowing the secret. This length extension attack has broken real API signing schemes. HMAC (RFC 2104) hashes the key and message in two nested passes and is immune.
Verifying a webhook signature (GitHub, Stripe and others use HMAC-SHA256):
import crypto from 'node:crypto';
function verifySignature(rawBody, headerHex, secret) {
const expected = crypto.createHmac('sha256', secret).update(rawBody).digest();
const received = Buffer.from(headerHex, 'hex');
// timingSafeEqual throws if lengths differ, so check first
if (received.length !== expected.length) return false;
return crypto.timingSafeEqual(expected, received);
}
const body = '{"event":"paid","id":42}';
// HMAC-SHA256(key="my-secret", body) =
// 9d0438ac042ff580675cd65158c5e8c3f54e03d03ea57084d666d1cdd3be907e
verifySignature(body, '9d0438ac…', 'my-secret'); // true with the full hex
verifySignature(body + ' ', '9d0438ac…', 'my-secret'); // false: one byte changedThe most common failure is framework middleware that parses JSON before your handler runs, so you hash a re-serialised body. Configure the route to give you the raw bytes. Use a constant-time comparison; a plain === on strings can leak how many leading characters matched.
Why SHA-256 Is Wrong for Passwords
SHA-256 is designed to be fast. A single modern GPU computes billions of SHA-256 hashes per second, so a leaked table of SHA-256 password hashes — even salted — falls quickly to dictionary and rule-based attacks. Password storage needs a function that is deliberately slow and memory-hard, with a per-user salt and an adjustable cost: Argon2id, scrypt, bcrypt or high-iteration PBKDF2.
crypto.createHash('sha256').update(password).digest('hex'); // ❌ fast, unsalted
import argon2 from 'argon2';
const hash = await argon2.hash(password, {
type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1,
}); // ✅ salted, slow, parameters stored in the stringParameters, upgrade strategy and the policy side are covered in How to Create Strong Passwords.
Check a digest in the browser
Compute MD5, SHA-1, SHA-256 and SHA-512 of any text locally — useful for confirming the examples above or debugging a mismatch. Nothing is uploaded.
Open Hash Generator →