TExcelTAD
Home › Cybersecurity › Encoding vs Hashing vs Encryption

Encoding vs Hashing vs Encryption

Three very different operations are often confused, and the confusion causes real vulnerabilities: passwords "protected" with Base64, data "encrypted" with a hash. The difference comes down to two questions: can it be reversed? and does reversing it need a secret?

Operation Purpose Reversible? Needs a key? Examples
Encoding Represent data in another format Yes, by anyone No Base64, hex, URL encoding, UTF-8
Hashing Fixed-size fingerprint of data No (one-way) No SHA-256, SHA-3, BLAKE2
Encryption Hide data from people without the key Yes, with the key Yes AES, ChaCha20, RSA

Encoding: format, not security

Encoding exists so data survives a channel that expects a certain format: binary inside JSON or email, spaces inside a URL. Anyone can decode it because the scheme is public and there is no key.

python · try it yourself
import base64
from urllib.parse import quote, unquote

secret = "admin:Sup3r$ecret"

b64 = base64.b64encode(secret.encode()).decode()
print("base64:", b64)
print("decoded:", base64.b64decode(b64).decode())

print("hex:", secret.encode().hex())
print("url:", quote(secret))
print("back:", unquote(quote(secret)))
base64: YWRtaW46U3VwM3IkZWNyZXQ=
decoded: admin:Sup3r$ecret
hex: 61646d696e3a5375703372246563726574
url: admin%3ASup3r%24ecret
back: admin:Sup3r$ecret

That Base64 string is exactly what HTTP Basic authentication sends in the Authorization header. It looks scrambled, but it is plain text to anyone who sees it. This is why Basic auth is only acceptable over HTTPS.

Warning: If you ever see "we encode the password in Base64 for security", that is a vulnerability, not a control.

Hashing: one-way fingerprints

A cryptographic hash function turns input of any size into a fixed-size digest. Good hash functions have three properties:

  1. Deterministic: the same input always gives the same digest.
  2. Avalanche effect: a tiny change in the input changes about half of the output bits.
  3. One-way and collision-resistant: you can't find an input for a given digest, or two inputs with the same digest.
python · try it yourself
import hashlib

for text in ["transfer 100 EUR", "transfer 100 EUR", "transfer 900 EUR"]:
    print(hashlib.sha256(text.encode()).hexdigest()[:32], text)

big = b"x" * 1_000_000
print(len(hashlib.sha256(b"").digest()), "bytes for empty input")
print(len(hashlib.sha256(big).digest()), "bytes for 1 MB input")
e298422468964759d755954e1ec35ab2 transfer 100 EUR
e298422468964759d755954e1ec35ab2 transfer 100 EUR
8df49afd780d5716ec6a8425008faf77 transfer 900 EUR
32 bytes for empty input
32 bytes for 1 MB input

There is no "unhash" function. Hashes are used to check integrity (did the file change?), to index data, and, with extra care, to store passwords. The next lessons cover each.

Encryption: secrecy with a key

Encryption transforms plaintext into ciphertext that only key holders can turn back. Modern encryption also detects tampering (authenticated encryption). Here is AES-GCM from the cryptography package, with a fixed demo key so the output is repeatable:

python · try it yourself
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = bytes(range(32))      # DEMO ONLY: real keys come from AESGCM.generate_key()
nonce = bytes(12)           # DEMO ONLY: never reuse a nonce with the same key
aes = AESGCM(key)

ciphertext = aes.encrypt(nonce, b"meet at 10:00", None)
print("ciphertext:", ciphertext.hex())
print("plaintext: ", aes.decrypt(nonce, ciphertext, None).decode())

try:
    AESGCM(bytes(32)).decrypt(nonce, ciphertext, None)
except Exception as err:
    print("wrong key:", type(err).__name__)
ciphertext: 63d9d0aa954df79d39989305280f9b461c982630fadfbf1b4c4414917c
plaintext:  meet at 10:00
wrong key: InvalidTag

The ciphertext is longer than the 13-byte message: AES-GCM appends a 16-byte authentication tag. Decrypting with the wrong key doesn't produce garbage; it fails with InvalidTag. The Symmetric Encryption lesson goes into detail.

Choosing the right tool

python · try it yourself
def choose(need):
    rules = [
        ("store passwords", "slow salted hash (scrypt, Argon2, PBKDF2)"),
        ("check a download wasn't corrupted", "hash (SHA-256)"),
        ("prove a message came from a key holder", "MAC (HMAC) or digital signature"),
        ("keep a file secret", "authenticated encryption (AES-GCM)"),
        ("put binary data in JSON", "encoding (Base64)"),
    ]
    for goal, tool in rules:
        if goal == need:
            return tool
    return "think again"

for need in ["put binary data in JSON", "store passwords", "keep a file secret"]:
    print(f"{need:<26} -> {choose(need)}")
put binary data in JSON    -> encoding (Base64)
store passwords            -> slow salted hash (scrypt, Argon2, PBKDF2)
keep a file secret         -> authenticated encryption (AES-GCM)

Common mistakes

  • Encoding as "encryption": Base64, ROT13 and XOR with a fixed byte protect nothing.
  • Encrypting passwords: if the key leaks, every password leaks. Store password hashes made with a slow KDF instead.
  • Hashing for secrecy: hashing a short or guessable value (a phone number, a 4-digit PIN) hides nothing, because anyone can hash every possibility and compare.
  • Inventing your own algorithm: use well-reviewed libraries; "home-made" crypto is almost always breakable.

Go further: Plaintext, Keys, Kerckhoffs and the Security Goals opens the Applied Cryptography course with the vocabulary and attacker models.

Test yourself

Which operation can anyone reverse without a key?

  1. Encryption
  2. Hashing
  3. Encoding
  4. Signing

What does the avalanche effect mean for a hash function?

  1. Hashes grow with the input
  2. A small input change gives a completely different digest
  3. Hashes can be reversed with enough time
  4. Similar inputs produce similar digests

Why should passwords not be stored encrypted?

  1. Encryption is too slow
  2. If the key leaks, all passwords can be decrypted
  3. Encrypted data can't be compared
  4. Encryption is illegal for passwords