Fingerprints for data
A cryptographic hash function is a one-way function: it takes any input, a word, a file, an entire disk, and produces a fixed-size output called a digest or hash. The output looks random; tiny input changes produce wildly different outputs.
A good hash function must promise three things:
- Pre-image resistance: given a hash, you can't recover the input.
- Second pre-image resistance: given an input, you can't find a different input with the same hash.
- Collision resistance: you can't find any two distinct inputs with the same hash.
When any of these break, the hash is dead. MD5 and SHA-1 have lost collision resistance; do not use them for security. SHA-256 and SHA-3 are the modern defaults. BLAKE3 is a newer, faster option.
Hashes are not encryption
This trips up almost everyone learning the field. A hash is not reversible, that's the point. There is no key that "unhashes" a value. People who promise to recover hashed passwords are either guessing (cracking) or lying.
Where hashes are useful
- Integrity checks: compare the hash of a downloaded file to a published one to detect tampering or corruption.
- Password storage: store a slow, salted hash so a database breach doesn't hand attackers the passwords directly.
- Content addressing: Git, IPFS, and container layers identify content by its hash.
- Inputs to signatures: digital signatures sign the hash of a message, not the message itself.
Passwords need slow hashes
For passwords specifically, use a hash designed to be slow: bcrypt, scrypt, or Argon2. SHA-256 alone is too fast, an attacker can try billions of guesses per second per GPU.
The missing piece: who made the hash?
A plain hash proves a message hasn't changed since it was hashed, but only if you trust the source of the hash. If both the message and its hash travel together, an attacker can change both. The hash alone proves nothing about who made it.
Two ways to fix this:
- MAC (Message Authentication Code). A hash that also takes a shared secret key. Only someone with the key can produce or verify it. HMAC is the standard construction (HMAC-SHA-256 is the common spelling).
- Digital signature. Asymmetric. The signer uses their private key; anyone with the matching public key can verify. Used when verifier and signer don't share a secret.
MAC vs. signature, in one line
Use a MAC when both parties share a secret. Use a signature when you need to convince a third party who only has a public key.
A worked mini-example
You send a friend a wire-transfer instruction over an open channel. Three escalating protections:
- Hash only: useless against a tamperer, since they can recompute the hash.
- HMAC with a shared key: now your friend can verify the message came from someone with the key, and hasn't been altered.
- Signature with your private key: now anyone with your public key can verify, including a bank arbitrator who never shared anything with you in advance.