Hash Functions Explained: SHA-256, HMAC and Safe Password Storage
What a cryptographic hash function does, how HMAC adds a secret key, and why passwords need slow hashes such as Argon2 or bcrypt instead of plain SHA-256.

A hash function takes any input, a word, a file or a whole disk image, and produces a short, fixed-size fingerprint called a hash or digest. Cryptographic hashes are everywhere: in passwords, digital signatures, software downloads, Git and blockchains.
What makes a hash “cryptographic”
A good cryptographic hash function such as SHA-256 has three properties:
- Pre-image resistance: given a hash, you cannot work out the input.
- Second pre-image resistance: given an input, you cannot find a different input with the same hash.
- Collision resistance: you cannot find any two inputs with the same hash.
Change a single character of the input and the hash changes completely. That is why hashes are used to check that a downloaded file has not been altered.
Current choices: SHA-256 and SHA-512 (the SHA-2 family), SHA-3, and BLAKE2/BLAKE3. Avoid MD5 and SHA-1 for security purposes; practical collisions have been demonstrated for both.
HMAC: a hash with a secret key
A plain hash proves that data has not changed, but anyone can compute it. HMAC (hash-based message authentication code) mixes a secret key into the hash. Only someone with the key can produce a valid HMAC, so it proves both integrity and authenticity.
HMAC is used to sign API requests, in web session tokens such as JWTs signed with HS256, and inside protocols like TLS.
Why passwords need a different kind of hash
It is tempting to store SHA-256(password). Don’t. SHA-256 is designed to be fast, and attackers with graphics cards can try billions of guesses per second against a stolen password database.
Passwords need hashes that are deliberately slow and memory-hungry, plus a unique random salt per user:
| Algorithm | Notes |
|---|---|
| Argon2id | The current recommended choice; tunable memory and time cost |
| scrypt | Memory-hard, widely available |
| bcrypt | Older but still acceptable with a sufficient cost factor |
| PBKDF2 | Acceptable when required for compliance, with a high iteration count |
The salt means two users with the same password get different hashes, and attackers cannot use precomputed tables.
Common mistakes
- Using MD5, SHA-1 or a single round of SHA-256 for passwords.
- Using the same salt for every user, or no salt.
- Comparing hashes with an ordinary string comparison in code, which can leak timing information. Use a constant-time comparison.
- Inventing your own scheme instead of using a well-tested library.
Key takeaways
- Hashes are fingerprints; use SHA-2, SHA-3 or BLAKE2/3.
- HMAC adds a secret key so only key holders can create a valid tag.
- Passwords need slow, salted hashing: Argon2id first, then scrypt, bcrypt or PBKDF2.
This guide was prepared with AI assistance.
Spotted an error or have more information? Contact the editor.