Cryptographic goals

Separate encoding, hashing, and encryption

Distinguish reversible representation, one-way digests, keyed authentication, and encryption so familiar APIs are not used for the wrong job.

Base64 changes how bytes are written. It provides no secrecy. Anyone can reverse it without any key:

const encoded = Buffer.from('secret-key').toString('base64')
Buffer.from(encoded, 'base64').toString() //secret-key

Encoding is a reversible representation. Base64, hex, and URL encoding exist so bytes survive transport through systems that expect text. That is the whole job.

A real application stored an API key as Base64 and labeled the column encrypted_key. Anyone who read the database could decode the value without a secret. The column name promised a security property the code never provided.

The four operations, side by side

A cryptographic hash maps data to a fixed-size digest. It is one-way: you cannot recover the input, and you cannot practically find two inputs with the same digest.

import { createHash } from 'node:crypto'

createHash('sha256').update('hello').digest('hex')
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Run it twice with the same input and you get the same digest. Change one character and the whole digest changes.

A MAC authenticates data with a shared secret. Without the key, an attacker cannot produce a valid tag. This matters because a plain hash cannot authenticate a webhook: an attacker who changes the body can calculate a fresh hash for the new body. Only the keyed version stops that.

Encryption makes plaintext recoverable only with a key, and in any modern design it should include authentication too. It is the only operation on this list meant to be reversed, and only by a key holder.

How to pick

The goal chooses the primitive. Need to transport bytes as text? Encode. Need a fingerprint or a change detector? Hash. Need to prove a message came from someone holding a shared secret? MAC. Need to hide content and get it back later? Encrypt.

If you catch yourself hashing something you will need to read back, or encoding something you need to keep secret, stop. The operation does not match the property.

Practice

Classify Base64, SHA-256, HMAC, password hashing, and authenticated encryption by input, key use, reversibility, and security property. Save one small result from each available API. Then modify or decode every result and record what the operation does not protect. The gaps you write down are the point of the exercise.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →