TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท security ยท cryptography ยท passwords ยท java ยท spring

Hashing vs encryption

Hashing is a one-way, fixed-size fingerprint of data, used for integrity checks and (slowly, with salt) for passwords; encryption is reversible with a key, used to keep data secret. HMACs and signatures add proof of who sent it, and Base64 is neither.

15 min6 animations

๐Ÿ–จ๏ธ Cheat sheet

A grinder and a suitcase

Picture a butcher's kitchen with two very different tools.

The first is a meat grinder. Put a steak in, turn the handle, and out comes mince, pressed into a patty. Two things make it special. The same steak always gives exactly the same patty. And there is no way back: nobody can turn mince into the steak it came from. Grinding like this is called hashing.

The second is a locked suitcase. You put something inside, lock it, and send it off. Anyone carrying it sees only the outside. Whoever has the key opens it and gets back exactly what you packed. Locking like this is called encryption.

So the question is always: do I need to get the thing back later? If yes, use the suitcase. If I only need to recognise it again, use the grinder.

One more thing gets mixed up with both: wrapping a steak in different paper. It looks different, but anyone can unwrap it, so it hides nothing.

One-way versus reversible

A cryptographic hash function maps input of any length to a fixed-size digest. SHA-256 always produces 256 bits (32 bytes, 64 hex characters). There is no key and no inverse: the digest is a fingerprint, not a container.

Encryption transforms plaintext into ciphertext with a key, and the matching key turns it back. Its job is confidentiality: the data must be recoverable, but only by key holders.

HashingEncryption
ReversibleNoYes, with the key
KeyNone (HMAC adds one)Required
Output sizeFixed (SHA-256: 32 bytes)Roughly the input size, plus nonce and tag
Used forIntegrity, passwords, ids, deduplicationKeeping data secret at rest and in transit

Rule of thumb: if you'll ever need the original back (a card number, a document), encrypt it. If you only need to check that something matches (a password, a download), hash it.

๐Ÿ”ง Going deeper

Encoding is neither. Base64, hex and URL encoding change the representation of bytes so they survive text-only channels. They use no key and anyone can reverse them, so they provide no secrecy and no integrity. A JWT payload, for example, is only base64url-encoded: readable by anyone (see JWT).

One-way hashing, two-way encryption4 steps
Patties012๐Ÿง‘โ€๐ŸณCookโš™๏ธMeat grinder๐ŸงณLocked suitcase๐Ÿ™‹Friend with the key
Press play and watch it happen!

Same steak, same patty

A good grinder has a few promises:

  • Same in, same out. The same steak gives the same patty, every time, in every kitchen.
  • Always one patty size. A tiny slice or a whole side of beef, the patty is always the same size.
  • Tiny change, totally different patty. Trim one sliver off the steak and the patty looks nothing like before.
  • No lookalikes. Nobody can find two different steaks that make the same patty.

That makes the grinder great for checking a delivery. The butcher grinds the steak and pins a photo of the patty on the shop's noticeboard. When your delivery arrives, you grind it yourself. Same patty? Nothing was swapped on the way. Different patty? Send it back.

Properties of a cryptographic hash

  • Deterministic: the same input always gives the same digest.
  • Fixed size: any input length gives a 256-bit digest for SHA-256.
  • Avalanche effect: flipping one input bit changes about half the output bits.
  • Preimage resistance: given a digest, you can't find an input that produces it.
  • Collision resistance: you can't find two different inputs with the same digest. MD5 and SHA-1 have practical collision attacks, so don't use them for anything security-related; use SHA-256, SHA-512 or SHA-3.

Integrity check: a publisher posts the SHA-256 of a release; you hash the downloaded file and compare. This only helps if the posted checksum comes from a channel you trust (an HTTPS page, or a signed file). An attacker who can swap the file and the checksum defeats it, because a plain hash has no secret in it.

1byte[] digest = MessageDigest.getInstance("SHA-256").digest(fileBytes);2String hex = HexFormat.of().formatHex(digest);   // Java 17+3boolean intact = hex.equalsIgnoreCase(publishedChecksum);
Checking a delivery with a hash4 steps
๐Ÿ”ชButcher๐ŸššDelivery van๐Ÿฝ๏ธRestaurant
Press play and watch it happen!

Keeping patties, not steaks

A restaurant lets regulars in with a secret steak only they own. The kitchen shouldn't keep everyone's steak in the fridge: a thief would take them all. So it keeps only the patty. When you come back, the chef grinds the steak you bring and checks it matches.

But a fast grinder causes trouble. If Ana and Ben own the same steak, their patties are the same, which gives them away. And a thief who steals the fridge can grind every common steak in the world, quickly, and keep a big book of what each patty looks like.

So the chef adds two things. First, a pinch of each person's own spice, called a salt, written on the label next to the patty. Now Ana's and Ben's patties differ, and the thief's book is useless. Second, a slow hand grinder that needs a thousand turns. You only wait a moment at the door, but the thief has to turn a thousand times for every guess, for every person.

Some kitchens also add a house spice kept in the chef's locked cupboard, never on the labels, so the stolen fridge alone isn't enough.

Password hashing: salts and slow functions

Store passwords as hashes, never encrypted (a stolen key would reveal them all) and never with a plain fast hash. SHA-256 runs billions of times per second on a GPU, so a leaked table of unsalted SHA-256 hashes falls to:

  • Brute force and dictionary attacks: hash every likely password and compare.
  • Rainbow tables: precomputed lookups from hash to common password.
  • Equal hashes: users with the same password have the same hash.

The fixes:

  • A salt: a unique random value per user, stored next to the hash. It isn't secret; it makes every hash unique and precomputed tables useless.
  • A slow, tunable password hash whose work factor sets the cost. OWASP's first choice is Argon2id (memory-hard), at least 19 MiB of memory, 2 iterations and parallelism 1; then scrypt. bcrypt is for legacy systems, with cost 10 or more, and it only uses the first 72 bytes of a password. Where FIPS-140 compliance is required, use PBKDF2-HMAC-SHA256 with 600,000 iterations.
  • Optionally a pepper: a secret added to every password and kept outside the database (in a secrets manager or HSM), so a database dump alone isn't enough.

These functions generate the salt and embed it, with the algorithm and cost, in the stored string, so you can raise the cost later and rehash on the next login.

1// encodes with bcrypt by default, stored as "{bcrypt}$2a$10$..."; the {id} prefix lets you migrate, e.g. to argon2@SpringSecurity_v5_82@Bean3PasswordEncoder passwordEncoder() {4    return PasswordEncoderFactories.createDelegatingPasswordEncoder();5}6 7String stored = encoder.encode(rawPassword);           // salted, slow8boolean ok = encoder.matches(attempt, stored);         // re-hashes with the stored salt9 10new BCryptPasswordEncoder(12);                         // explicit cost, default is 1011Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); // 16 MiB, t=2, p=1; needs Bouncy Castle12new Argon2PasswordEncoder(16, 32, 1, 19456, 2);         // OWASP minimum: 19 MiB, t=2, p=1

Tune the cost so one check takes a noticeable fraction of a second on your servers, and rate-limit login attempts.

Storing passwords5 steps
Plain patty fridge012Spiced patty fridge012๐Ÿ™‹Ana and Ben๐Ÿง‘โ€๐ŸณChef
Press play and watch it happen!

A spice only two people know

The noticeboard check only works when you can see the butcher's own noticeboard. When the photo has to travel taped to the box, a crook on the road can swap the steak and the photo together. So the butcher and the restaurant agree on a shared spice that nobody else has. The butcher grinds each delivery together with that spice and tapes the patty to the box.

The restaurant grinds the steak with the same spice. If the patties match, the steak is untouched and really came from the butcher. A crook on the road can make a patty too, but without the spice it never matches. This spiced patty is called an HMAC.

HMAC: integrity plus authenticity

An HMAC (hash-based message authentication code) mixes a shared secret key into the hash: HMAC-SHA256(key, message). Only key holders can compute a valid tag, so a matching tag proves the message wasn't altered and came from someone with the key. A plain SHA-256(message) can't do that: an attacker who changes the message simply recomputes it.

Typical uses: webhook signatures (Stripe, GitHub), signed cookies, HS256 JWTs, and API request signing. HMAC gives no secrecy (the message travels in clear) and, since both sides hold the key, it can't prove which of them produced a tag. Use HMAC rather than hash(key + message), which is open to length-extension attacks with SHA-256.

1Mac mac = Mac.getInstance("HmacSHA256");2mac.init(new SecretKeySpec(sharedKey, "HmacSHA256"));3byte[] expected = mac.doFinal(body);4boolean authentic = MessageDigest.isEqual(expected, receivedTag);  // constant-time compare
HMAC proves who sent it3 steps
๐Ÿ”ชButcher๐ŸฆนCrook on the road๐Ÿฝ๏ธRestaurant
Press play and watch it happen!

One key for both

Now the suitcase. The simplest kind has one key, and you and your friend each hold a copy. You lock it, send it, and your friend unlocks it. Using the same key both ways is called symmetric encryption.

A good suitcase has two extras. A tamper seal: if anyone pries it open or swaps what's inside, your friend sees the broken seal and refuses it. And a combination dial you set to a fresh number every single time you lock it. Use the same number twice with the same key and a snoop comparing the two suitcases can learn a lot about what's inside both, and even fake a seal that looks whole.

Symmetric encryption: AES-GCM

Symmetric ciphers use one secret key to encrypt and decrypt. They're fast, so they protect almost all bulk data: disks, database fields, and every byte after a TLS handshake. The standard choice is AES (128 or 256-bit keys) in GCM mode, an authenticated encryption (AEAD) mode: it outputs ciphertext plus an authentication tag (use the full 128 bits), and decryption fails if a single bit of ciphertext, tag or associated data changed.

GCM needs a nonce (IV), usually 12 bytes, that must never repeat for the same key. Reuse leaks the XOR of the two plaintexts and lets attackers forge tags. Generate it randomly (and rotate keys well before about 2^32 messages) or use a counter, and store it next to the ciphertext; it isn't secret. Avoid ECB mode, and unauthenticated modes like CBC without a MAC.

1KeyGenerator kg = KeyGenerator.getInstance("AES");2kg.init(256);3SecretKey key = kg.generateKey();4 5byte[] iv = new byte[12];6new SecureRandom().nextBytes(iv);                       // fresh nonce every time7 8Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");9cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));10byte[] ciphertext = cipher.doFinal(plaintext);          // ciphertext with the tag appended11// decrypt: Cipher.DECRYPT_MODE with the same iv; a tampered message throws AEADBadTagException

The hard part is key management: keep keys out of code and the database, in a KMS or secrets manager (see AWS KMS).

One key, a seal and a fresh dial number4 steps
Luggage room012๐Ÿง‘โ€๐ŸณYou๐Ÿ™‹Friend
Press play and watch it happen!

Open padlocks and a wax seal

Sharing one key is awkward: how do you get a copy to a stranger safely? So Bob hands out open padlocks. Anyone can snap one shut on a suitcase, but only Bob's own key opens it. The padlocks are his public key; the key he never lets go of is his private key. Ana must be sure a padlock is really Bob's, not one the porter swapped in.

It also works the other way round. Bob presses a wax seal that only he owns onto a note, and anyone can check it against the seal picture Bob hands out with his padlocks, to know it's really his and untouched. That's a signature.

Padlocks are slow and fiddly, so in practice people use one only to send a small suitcase key, then switch to the quick one-key suitcase.

Asymmetric encryption and signatures

Asymmetric (public-key) cryptography uses a key pair. The public key can be shared with anyone; the private key never leaves its owner. The catch is knowing a public key really belongs to its owner: an attacker who swaps in their own key reads everything. Certificates solve that (see TLS).

  • Encryption: anyone encrypts with the public key; only the private key decrypts (RSA-OAEP, or ECIES-style schemes on elliptic curves).
  • Signatures: the owner signs a hash of the message with the private key; anyone verifies with the public key (RSA-PSS, ECDSA, Ed25519). Unlike HMAC, only one party could have produced it, which gives non-repudiation.

Public-key operations are slow and RSA can only encrypt a small block, so real systems are hybrid: key exchange (ECDHE in TLS) or RSA agrees on a symmetric key, and AES-GCM encrypts the data. Signatures are what certificates, RS256/ES256 JWTs, signed commits and software releases rely on.

1Signature signer = Signature.getInstance("SHA256withECDSA");2signer.initSign(keyPair.getPrivate());3signer.update(document);4byte[] signature = signer.sign();5 6Signature verifier = Signature.getInstance("SHA256withECDSA");7verifier.initVerify(keyPair.getPublic());8verifier.update(document);9boolean genuine = verifier.verify(signature);
Padlocks and seals4 steps
๐Ÿง‘โ€๐ŸณAna๐Ÿ•ต๏ธNosy porter๐Ÿ™‹Bob
Press play and watch it happen!
๐Ÿ”ง Going deeper

Choosing quickly:

NeedUse
Store passwordsArgon2id, scrypt or bcrypt with salt (never SHA-256, never encryption)
Detect accidental or untrusted-mirror changesSHA-256 checksum from a trusted source
Prove a message came from a partner sharing a secretHMAC-SHA256
Prove who signed it, verifiable by anyoneSignature (Ed25519, ECDSA, RSA-PSS)
Keep data secret and tamper-evidentAES-GCM (or ChaCha20-Poly1305)
Send a secret to someone you share no key withPublic-key encryption or key exchange, then AES-GCM
Fit bytes into textBase64 (no security at all)

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Hashing vs encryption, told the same way as the story.
  1. The kitchen must keep a customer's card and later hand it to the bank, which must read it. Grinder or suitcase?
  2. Ana and Ben own the same steak. Why should the chef add each person's own spice before grinding?
  3. Why does the chef use a slow hand grinder for regulars' steaks instead of the fast electric one?
  4. A crook on the road swaps the steak and grinds a fresh patty to tape on the box. What stops him?
  5. You lock two suitcases with the same key and the same dial number. What goes wrong?
Answer every question to check.Passing marks Hashing vs encryption as done.
Got the hang of Hashing vs encryption? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ›ก๏ธ Signing in safelyStep 2 of 5

โ† Previous on the path๐Ÿ“ฎ HTTPNext on the path โ†’๐Ÿšง CORS