Sikau

Security · Day 9 · about 40 min

Encrypting data

AES-GCM with a fresh nonce: secrecy plus tamper detection.

Some secrets must come back

A password is never needed again, so you hash it. But a phone number, an address or an API key you must read later. That is a job for encryption: scramble the data with a secret key, and anyone holding the key can unscramble it. Without the key, the bytes are noise.

Picture Asha's momo shop storing delivery addresses. If the database leaks and the addresses are encrypted with a key kept elsewhere, the thief gets nothing readable. If they are plain text, every customer's home is exposed.

AES-GCM and the nonce

Use AES-GCM. It does two things at once: it hides the data, and it attaches an authentication tag so any change to the ciphertext is detected when you decrypt. Old modes such as ECB or plain CBC hide data but let attackers flip bits unnoticed.

GCM needs a nonce (also called an IV): 12 bytes that must be unique for every encryption under the same key. It is not secret, so store it next to the ciphertext. Reusing a nonce with the same key breaks GCM badly: an attacker can learn the XOR of two messages and forge tags.

const toHex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
const fromHex = (hex) => Uint8Array.from(hex.match(/../g) ?? [], (h) => parseInt(h, 16));

async function aesKey(keyHex, usage) {
  return crypto.subtle.importKey("raw", fromHex(keyHex), "AES-GCM", false, [usage]);
}

async function encrypt(text, keyHex, ivHex = toHex(crypto.getRandomValues(new Uint8Array(12)))) {
  const key = await aesKey(keyHex, "encrypt");
  const data = new TextEncoder().encode(text);
  const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv: fromHex(ivHex) }, key, data);
  return ivHex + ":" + toHex(sealed);
}

async function decrypt(payload, keyHex) {
  const [ivHex, sealedHex] = String(payload).split(":");
  if (!ivHex || !sealedHex) throw new Error("Malformed payload");
  try {
    const key = await aesKey(keyHex, "decrypt");
    const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromHex(ivHex) }, key, fromHex(sealedHex));
    return new TextDecoder().decode(plain);
  } catch {
    throw new Error("Tampered");
  }
}

The rest of this lesson

  • Keys, not clevernessexplain
  • Flip one bytepredict
  • Sealing a messageorder
  • Hash, encrypt or sign?match
  • Seal and openwrite code
  • Badge quizquiz
  • What you learnedrecap