Skip to lesson

Hashing vs encryption vs encoding

A developer stores a password "safely" as Base64, or encrypts one that should have been hashed. The three tools look alike but solve different problems, and picking the wrong one leaves the data open.

Encoding: a new format, not a secret

Encoding writes the same data in a different format so it can travel safely through a system. Anyone who knows the format can turn it back without a key, so encoding gives no secrecy.

A made-up login is Base64-encoded and decoded again with no key, and a search text is URL-encoded.

Example 1 · Base64 and URL encoding, there and back

Terminal
printf 'asha:campus123' | base64printf 'YXNoYTpjYW1wdXMxMjM=' | base64 -dcurl -sv -G https://httpbin.org/get --data-urlencode "q=Rs 1,299 & free" -o /dev/null 2>&1 | grep '^> GET'
Output
YXNoYTpjYW1wdXMxMjM=
asha:campus123
> GET /get?q=Rs+1%2c299+%26+free HTTP/1.1

What this code does

  • base64 encodes the made-up login asha:campus123, and base64 -d decodes it back with no key at all. This exact text travels in the HTTP Basic login header, which is why Basic login is only safe inside HTTPS.
  • --data-urlencode makes curl URL-encode the search text: the space becomes +, the comma %2c and the & %26. Without this, the & would split the value into two query parameters. The server decodes it back to Rs 1,299 & free.

Base64 turns any bytes into 64 safe characters (A–Z, a–z, 0–9, + and /), with = as padding at the end. It is used where only plain text may travel: email attachments, the HTTP Basic login header and the parts of a signed token. URL encoding (percent-encoding) replaces characters that have a meaning in a URL, such as a space, & or a comma, with % and a two-digit hex code: & becomes %26.

Encoding is like Morse code: it looks strange to a person, but every Morse chart in the world reads it back.

If someone says "the password is safe, it is Base64-encoded", the password is not safe. Base64 is a format, not a lock.

Encryption: locked with a key

Encryption turns readable data (the plaintext) into unreadable data (the ciphertext) using a key, a long secret value. Only someone with the right key can decrypt it back.

Two ways to lock the same message: one shared key, or a key pair with a public and a private half.

Example 2 · Symmetric and asymmetric encryption in one picture

Text
SYMMETRIC: one shared key K (two friends with copies of one locker key)  "Pay Rs 500 to Ravi"  --encrypt with K-->  9f 3a c1 7e 52 ...  9f 3a c1 7e 52 ...    --decrypt with K-->  "Pay Rs 500 to Ravi"ASYMMETRIC: a key pair (a post box: anyone drops letters in, one key opens it)  "Pay Rs 500 to Ravi"  --encrypt with Ravi's PUBLIC key-->   4b e0 92 d8 ...  4b e0 92 d8 ...       --decrypt with Ravi's PRIVATE key-->  "Pay Rs 500 to Ravi"  (the ciphertext bytes are made up to show the shape)
Where each one fits
Symmetric   fast, fine for lots of data; both sides need the same secret key
Asymmetric  slow, used for small jobs; the public key can be shared openly
HTTPS       public-key maths to agree on a fresh shared key, then symmetric for the data

What this code does

  • With symmetric encryption the hard part is sharing K safely: whoever sees K on the way can read everything. Asymmetric keys remove that problem, because the public key may be seen by anyone.
  • Real systems combine them. HTTPS uses public-key maths only to agree on a fresh symmetric key, then uses fast symmetric encryption for the actual pages and API calls. The next lesson walks through it.

Symmetric encryption uses one shared key to lock and unlock, like a locker whose key two friends have copies of. It is fast, so it protects large amounts of data, but both sides must already share the secret key. AES is the common example.

Asymmetric encryption uses a key pair: a public key that anyone may have and a private key that only the owner keeps, like a college post box where anyone can drop a letter in but only the office key opens it. It is much slower, so it is used for small jobs such as agreeing on a key or proving identity. RSA and elliptic-curve keys are common examples.

Hashing: a one-way fingerprint

A hash, also called a digest, is a fixed-length value that a hash function makes from any input. It works one way only: there is no key and no way to turn the hash back into the input.

The same text always gives the same hash, and one changed character gives a completely different one.

Example 3 · SHA-256: same input, same hash; one character changed, a new hash

Terminal
printf 'campus123' | openssl dgst -sha256printf 'campus123' | openssl dgst -sha256printf 'campus124' | openssl dgst -sha256printf 'Order 17 for Asha Rao: 1 x Clean Code, 2 x boAt Airdopes 141, total Rs 3097.00' | openssl dgst -sha256
Output (OpenSSL 3; older versions print SHA256(stdin)= or (stdin)= before the same hash)
SHA2-256(stdin)= 4cb48ed6cefe9853cacd04ff0781db81bcdc417641761b637addc5cc000b2c69
SHA2-256(stdin)= 4cb48ed6cefe9853cacd04ff0781db81bcdc417641761b637addc5cc000b2c69
SHA2-256(stdin)= 9f96f1fc2410fd5fc085c06478101a2ad641ce3c0fadd149f455f8617ff19e83
SHA2-256(stdin)= b02e8ad5f84659a3c79dd3a659c575fec1fa8ba0599ec6af8ea3c785a0627e7d

What this code does

  • The first two lines are identical: hashing is repeatable, so a server can compare hashes instead of secrets. Changing only the last character, 3 to 4, gives a hash with nothing in common with the first one. That is the avalanche effect.
  • The long order line still gives exactly 64 hex characters. The hash has a fixed length whatever the input size, so it cannot contain the input: there is nothing to decrypt.

A good hash has three properties. The same input always gives the same hash, so you can compare two hashes instead of two secrets. A tiny change in the input gives a totally different hash, called the avalanche effect. And it is practically impossible to find two different inputs with the same hash (a collision).

SHA-256 is the common choice today and always gives 256 bits, written as 64 hex characters. MD5 and SHA-1 are older and broken: people have built real collisions for both, so they must not be used for security.

Passwords: hashed, never encrypted

A salt is a random value, different for every user, mixed into a password before hashing and stored next to the hash. Two users with the same password then get different hashes.

Two customers chose the same password. Here is what a thief sees when it is stored in three different ways.

Example 4 · Three ways to store the same password

Text
Two customers both chose the password campus123. A stolen table would show:Stored as plain text  asha.rao@example.com    campus123  ravi.kumar@example.com  campus123Stored as fast SHA-256, no salt  asha.rao@example.com    4cb48ed6cefe9853cacd04ff0781db81bcdc417641761b637addc5cc000b2c69  ravi.kumar@example.com  4cb48ed6cefe9853cacd04ff0781db81bcdc417641761b637addc5cc000b2c69Stored as BCrypt (cost 12, a new random salt for each user)  asha.rao@example.com    $2a$12$j20OWFUeAC0DkqbuLU33Fuxg9o.o/taoYoCNBT.J8t8VkrB2F6QsS  ravi.kumar@example.com  $2a$12$hr36xPjdlQBUBgCcX1P3bu3WCnhrb3rxctoyMdHR5CTjTpIdKpu2C
What the attacker learns
Plain text  every password is readable at once
SHA-256     equal hashes reveal equal passwords; a rainbow table finds campus123 instantly
BCrypt      every row differs; each single guess costs about half a second on a laptop

What this code does

  • A BCrypt value packs everything into one 60-character string: $2a$ is the BCrypt version, 12 is the cost (2¹² rounds of work), the next 22 characters are the salt and the last 31 are the hash. At login the server reads the salt and cost from the stored string and hashes the typed password the same way.
  • Both BCrypt rows hold campus123, yet they share nothing, because each user got their own salt. An attacker must guess every user's password separately, and each guess is slow on purpose.

A server never needs to read a password back; it only checks that the password typed at login matches the one chosen at sign-up. So it stores a password hash and hashes the typed password the same way at login. Encryption would be wrong: anyone who steals the database and the key (they often sit on the same server) gets every password in plain text.

A plain fast hash is still not enough, because attackers keep rainbow tables: huge precomputed lists of common passwords and their hashes. The salt makes those tables useless, and the hash must also be slow on purpose. SHA-256 and MD5 are built to be fast, and a graphics card computes billions per second. BCrypt and Argon2 have a cost setting that makes each guess take a noticeable fraction of a second, and Argon2 also needs a lot of memory per guess.

Find the bug

Find the password bug

Each snippet stores or checks a password. Tap the unsafe line, then check the fix.

Store a new customer password.

Round 1 of 3
Never invent your own scheme ("SHA-256 twice plus a secret word"). Use the framework's password encoder: the Users & Password Storage module sets up BCrypt for ShopLite.

Signatures and HMAC: proving data was not changed

An HMAC is a tag made by hashing data together with a secret key; a digital signature is a tag made with a private key and checked with the matching public key. Both prove the data was not changed, and neither hides it.

A signed token has two parts: readable data and a tag. Decoding the first part of a real token shows that the data is only encoded.

Terminal
printf 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' | base64 -d
Output
{"alg":"HS256","typ":"JWT"}

Example 5 · How an HMAC catches a changed token

Text
HMAC (one secret key, kept only on the server)  data = {"sub":"1","role":"CUSTOMER"}  tag  = HMAC-SHA256(data, server secret)        -> sent to the client with the data  When the token comes back:  recompute HMAC-SHA256(data, server secret) and compare it with the tagDIGITAL SIGNATURE (a key pair)  signature = sign(data, PRIVATE key)            only the key owner can make it  verify(data, signature, PUBLIC key)            anyone with the public key can check it
What happens to a changed token
Token unchanged                    -> recomputed tag matches -> accepted
role edited to ADMIN, old tag kept -> tags differ            -> rejected (401)
role edited, new tag made up       -> impossible without the server secret
Reading the data                   -> always possible: it is only Base64-encoded

What this code does

  • The tag depends on every character of the data and on the secret. Change one letter and the recomputed tag is completely different, the same avalanche effect as in Example 3.
  • An HMAC needs one shared secret, so only servers that know it can check it. A signature lets other services check the token with the public key, without ever being able to make new ones. The JWT Authentication module uses an HMAC (HS256) for ShopLite.

This is the idea behind signed tokens. The server puts readable data such as "customer 1, role CUSTOMER" in the token and adds a tag. When the token comes back, the server recomputes the tag; if anyone changed even one character, for example CUSTOMER to ADMIN, the tags no longer match and the server rejects the token.

Because the data is only encoded, anyone holding a signed token can read it. Never put a password or any other secret inside one.

Example 6 · Choosing the right tool: real cases

Text
Data                                Tool                                  WhyUser passwords                      slow salted hash (BCrypt, Argon2)     only checked, never read backCard numbers                        do not store; keep the gateway token  RBI card rules (Oct 2022)Phone number, delivery address      encryption, key kept outside the DB   must be read back to deliverPassword-reset, refresh tokens      long random value; store its hash     only compared, like a passwordLogin token given to the client     HMAC or digital signature             server must detect any editSearch text in a URL, file in JSON  URL encoding, Base64                  format only, no secrecyEverything on the network           HTTPS (TLS)                           encrypted and checked in transit
The four questions
Need to read it back later?      -> encryption, with the key kept out of code and database
Only need to check it matches?   -> hashing (slow and salted for passwords)
Need to prove it was not changed? -> HMAC or signature
Only need a safe format?         -> encoding, never for secrets

What this code does

  • Ask what you need to do with the data later. Reading it back needs encryption; only checking it needs a hash; trusting it needs a tag; moving it needs encoding. Card numbers are a special case: in India, RBI rules since October 2022 stop most merchants from storing full card numbers, so shops keep a token from the payment gateway instead.
  • A reset token is a long random value, so a fast hash such as SHA-256 is fine for it: there is no short list of likely values to guess. Passwords are chosen by people, often weakly, which is why they need the slow, salted kind.

Next step

Check your understanding

12 quick questions