cybersecurity / cryptography
Cryptography for Programmers: Hashing vs Encryption vs Signing
The distinction that trips up most beginners, demonstrated with a short Node.js script you can run: a hash, an HMAC, an AES-GCM ciphertext and an Ed25519 signature over the same message. Then the free books and courses that go deeper, with the math you need and the math you can skip.
Ask ten developers whether a password database should be "encrypted" or "hashed" and you will get confident, conflicting answers. The confusion comes from treating cryptography as one skill when it is a small set of tools that each answer a different question. Does the data need to stay secret? Does it need to prove it has not changed? Does it need to prove who created it? Once you can map a requirement to the tool that answers it, most of the beginner mistakes disappear, such as encrypting when you needed a signature, or hashing a password with a fast algorithm built for file checksums.
01 · MATCH THE TOOL TO THE QUESTION
Three questions decide the tool
Start with what you need, not with an algorithm name.
| You need to... | Use | Key involved | Reversible? |
|---|---|---|---|
| Fingerprint data, so identical input gives an identical short value | Hash (SHA-256) | None | No |
| Hide data from everyone without the key | Encryption (AES-GCM) | One shared secret key | Yes, with the key |
| Detect tampering when both sides share a secret | MAC (HMAC-SHA256) | One shared secret key | No |
| Prove who created data, verifiable by anyone | Digital signature (Ed25519) | Private key signs, public key verifies | No |
| Store a password you must check later | Slow password hash (Argon2id) | None, plus a salt | No |
The key column is the one people skip. A hash has no key, so anyone can compute it. That sounds like a detail until you see what it implies.
02 · RUN IT
One message, four operations
This script uses only the node:crypto module that ships with Node.js. It takes the message "pay Alice 100" through each tool and reports what an attacker can and cannot do. Save it as demo.mjs and run node demo.mjs.
import { createHash, createHmac, randomBytes, createCipheriv, createDecipheriv, generateKeyPairSync, sign, verify, timingSafeEqual } from 'node:crypto'; const msg = Buffer.from('pay Alice 100'); // 1. Hash: no key, so an attacker can recompute it for any message const h = (b) => createHash('sha256').update(b).digest('hex'); console.log('sha256(pay Alice 100) =', h(msg)); console.log('sha256(pay Alice 101) =', h('pay Alice 101')); // 2. HMAC: a hash that needs a shared key const key = randomBytes(32); const tag = createHmac('sha256', key).update(msg).digest(); const good = createHmac('sha256', key).update(msg).digest(); const bad = createHmac('sha256', randomBytes(32)).update(msg).digest(); console.log('hmac, same key :', timingSafeEqual(tag, good)); console.log('hmac, other key:', timingSafeEqual(tag, bad)); // 3. Encryption: AES-256-GCM, reversible with the key and tamper-evident const iv = randomBytes(12); const c = createCipheriv('aes-256-gcm', key, iv); const ct = Buffer.concat([c.update(msg), c.final()]); const at = c.getAuthTag(); const d = createDecipheriv('aes-256-gcm', key, iv); d.setAuthTag(at); console.log('decrypts to:', Buffer.concat([d.update(ct), d.final()]).toString()); const flipped = Buffer.from(ct); flipped[0] ^= 1; const d2 = createDecipheriv('aes-256-gcm', key, iv); d2.setAuthTag(at); try { d2.update(flipped); d2.final(); } catch (e) { console.log('tampered ciphertext rejected:', e.message); } // 4. Signature: private key signs, anyone with the public key verifies const { publicKey, privateKey } = generateKeyPairSync('ed25519'); const sig = sign(null, msg, privateKey); console.log('signature bytes:', sig.length); console.log('verify original:', verify(null, msg, publicKey, sig)); console.log('verify altered :', verify(null, Buffer.from('pay Alice 900'), publicKey, sig));
sha256(pay Alice 100) = 74dcc4588f21379e343ea26c278458b51e98c5993dd01ae044735630ce4de2e9 sha256(pay Alice 101) = 765321770c05335c71143cc2ee51f0907170364e4bf4f4011d6c5b1a370c4155 hmac, same key : true hmac, other key: false decrypts to: pay Alice 100 tampered ciphertext rejected: Unsupported state or unable to authenticate data signature bytes: 64 verify original: true verify altered : false
Read the output against the table. Changing one character, 100 to 101, produces a completely different SHA-256 digest, which is why hashes work as fingerprints. But the hash gives no protection against someone who can alter the message: they change it and recompute the hash, and the two agree again. Only the HMAC and the signature involve a secret an attacker lacks. AES-GCM does double duty: it hides the content and rejects the modified ciphertext. The difference between the HMAC and the signature is who can check them. Anyone holding the HMAC key can also forge tags. A signature can be verified by anyone with the public key, while only the private key holder can create it.
03 · THE PASSWORD EXCEPTION
Why a password hash should be slow
SHA-256 is built to be fast, which is exactly wrong for passwords. If a database of fast hashes leaks, an attacker can test billions of guesses per second. Password hashing uses deliberately expensive functions with a per-user salt. OWASP's Password Storage Cheat Sheet recommends Argon2id with a minimum configuration of 19 MiB of memory, an iteration count of 2 and a parallelism of 1. If Argon2id is not available it recommends scrypt, and it lists bcrypt for legacy systems. Latacora's "Cryptographic right answers" gives its own ordering: scrypt, argon2, bcrypt, then PBKDF2 if nothing else is available. Use the library function your framework provides; do not assemble one from the primitives above.
- OWASP Password Storage Cheat Sheet ↗Argon2id parameters, scrypt and bcrypt fallbacks, salts, peppers and how to upgrade a work factor over time.cheatsheetseries.owasp.org
- Latacora: Cryptographic right answers ↗One recommendation per task, such as randomness, passwords, symmetric encryption and signatures, written for people who ship software.latacora.com
04 · GUARDRAILS
Rules that keep real systems out of trouble
Pick algorithms from a current standard, not from a tutorial's age. NIST deprecated SHA-1 in 2011 and disallowed it for digital signatures at the end of 2013; its hash function page lists the approved SHA-2 and SHA-3 families. A tutorial that uses SHA-1 or MD5 for anything security-related is out of date.
Never reuse a nonce with the same key. The iv in the script must be unique for every message encrypted under one key. OWASP's Cryptographic Storage Cheat Sheet points to NIST SP 800-38D for the specific requirements on AES-GCM input lengths and IV construction. Repeating one breaks the guarantees.
Use authenticated encryption. AES with a key of at least 128 bits, ideally 256, and a secure mode, as OWASP puts it. In practice that means GCM or a similar authenticated mode, not bare AES in ECB or unauthenticated CBC.
Keys are the real secret. Where a key lives, who can read it and how it rotates matter more than the cipher. The best algorithm in the world fails when the key is in the repository.
05 · WHERE TO LEARN MORE
Free books, courses and challenges, and the math you need
You can use cryptography correctly without proving theorems. Programmer-focused material needs modular arithmetic and probability at most. Move to the theory-heavy sources when you want to understand why the constructions are secure.
| Resource | Format | Math level | Cost |
|---|---|---|---|
| Crypto 101 | Book (PDF, EPUB, Mobi) | Light; written for programmers | Free |
| Cryptopals challenges | Eight sets of coding exercises | Grows by set; abstract algebra in set 8 | Free |
| Khan Academy cryptography unit | Videos and exercises | Light | Free |
| Boneh and Shoup, A Graduate Course in Applied Cryptography | Book, version 0.6 (Jan. 2023) | Heavy; proofs | Free download |
| Cryptography I (Dan Boneh) | Coursera, 7 modules | Moderate | Not stated on the course page; check enrollment options |
- Crypto 101 ↗A free introductory book covering block and stream ciphers, hashes, MACs, public-key encryption, key agreement and signatures, with enough to understand TLS.crypto101.io
- The Cryptopals Crypto Challenges ↗Eight sets, from basics through block and stream crypto to RSA, hashes and abstract algebra. Based on real-world vulnerabilities, not puzzles.cryptopals.com
- A Graduate Course in Applied Cryptography ↗Dan Boneh and Victor Shoup's textbook, available to download, from secret-key encryption through signatures and protocols.toc.cryptobook.us
- Cryptography I, Stanford (Coursera) ↗Dan Boneh's course: seven modules, listed at about two weeks at 10 hours a week, with a shareable certificate. The page does not state what is free, so check the enrollment options.coursera.org
- Khan Academy: Cryptography ↗From ancient ciphers to modern ones, a gentle first look before you open a programmer-oriented book.khanacademy.org
06 · FAQ
Frequently asked questions
Do I need to be good at math to learn cryptography?
Not to start. Programmer-focused material such as Crypto 101 and the early Cryptopals sets needs little more than basic modular arithmetic. The theory-heavy sources, such as the Boneh and Shoup textbook, use proofs and are worth tackling later.
What is the difference between hashing and encryption?
Encryption is reversible: with the key you recover the original data. A hash is a one-way fingerprint of fixed length that cannot be reversed. Use encryption to keep data secret and hashing to compare or fingerprint it. Hashing alone does not stop tampering, since anyone can recompute it.
How is a digital signature different from an HMAC?
Both detect modification. An HMAC uses one shared secret, so anyone who can verify it can also forge it. A signature uses a private key to sign and a public key to verify, so only the owner can create it while anyone can check it.
Should I write my own encryption?
No. Use a well-reviewed library and a standard authenticated mode. Most real-world cryptographic failures come from how primitives are combined, such as reusing a nonce, not from the primitives themselves.
What are the Cryptopals challenges?
They are a free set of programming exercises in eight sets, from basics through block and stream ciphers to RSA, hashes and abstract algebra. Each is based on a real-world vulnerability, and you implement the attack yourself.