← Lessons/Encoding, Hashing, HMAC & Encryption

Encoding, Hashing, HMAC & Encryption

JWTs, TLS certificates, and SSH keys are built from a small set of primitives. Engineers mix these four up all the time, and the mix-ups cause real incidents:

PrimitiveNeeds a key?Reversible?What it proves
Encoding (base64)noyes, by anyonenothing; it's a format change
Hashing (SHA-256)nonothe bytes haven't changed (integrity)
HMAC (HMAC-SHA256)a shared secretnothe bytes haven't changed and came from someone with the secret (authenticity)
Encryption (AES)a secret keyyes, with the keyonly key holders can read it (confidentiality)

This lesson runs each one on real files, so you'll recognise which one you're looking at when you meet it later.

Your script builds up across the steps: each step opens with the previous step's script in the editor, so keep your earlier lines.

securitycryptographybase64sha256hmacopenssl

Interview prep

Interviewers use this to see whether you really understand security or just repeat buzzwords. Be precise about what each primitive does and doesn't guarantee.

A teammate says the database password is safe because it's base64-encoded in the Kubernetes Secret. What do you tell them?

Base64 is an encoding, not encryption. It has no key, and anyone who can read the Secret can run base64 -d on it. Real protection comes from access control on the Secret (RBAC), encryption at rest in etcd, or an external secrets manager. Base64 is only there so binary values fit in YAML.

What's the difference between a hash and an HMAC, and when do you need the HMAC?

A hash such as SHA-256 proves integrity: the bytes match a known digest. But anyone can compute a hash, so an attacker who can change the data can change the hash too. An HMAC mixes in a shared secret, so only key holders can produce a valid tag. That proves the data is unmodified and came from someone with the key. You need HMAC to authenticate a sender, for example webhook signatures or HS256 JWTs.

Why use HMAC instead of sha256(secret + message)?

Merkle–Damgård hashes such as SHA-256 are vulnerable to length-extension. Given sha256(secret + message), an attacker can compute a valid digest for message + extra bytes without knowing the secret. HMAC's nested construction (hash of key-derived pads around an inner hash) isn't vulnerable to that, so it's the standard way to key a hash.