BBackend CourseLeroy Labs
0/0
Search the course

Encryption at rest with AES-GCM in your application

Symmetric encryption fundamentals, why AES-GCM (authenticated), nonces/IVs, ciphertext format with key id, what to encrypt vs hash, and disk/DB encryption layers.

● expertIR3D (Kontentt)SperoTek (in dev)

Hash or encrypt?

Data Need to read it back? Use
Passwords, recovery codes, reset tokens, refresh tokens No, only compare Hash
TOTP secrets, third-party OAuth tokens, bank details, queued email bodies Yes Encrypt
Data you can avoid storing n/a Don’t store it (the best option)

AES-GCM

AES is a block cipher. GCM is a mode that provides confidentiality plus integrity (an authentication tag). If anyone flips a bit in the ciphertext, decryption fails instead of returning garbage. Never use ECB, and prefer GCM over CBC.

public final class KeyRingCipher {
    private static final int IV_LEN = 12, TAG_BITS = 128;
    private final SecureRandom rng = new SecureRandom();

    public String encrypt(String plaintext) throws GeneralSecurityException {
        byte[] iv = new byte[IV_LEN];
        rng.nextBytes(iv);                                   // UNIQUE per encryption
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, activeKey(), new GCMParameterSpec(TAG_BITS, iv));
        c.updateAAD(activeKeyId().getBytes());               // binds the key id to the ciphertext
        byte[] ct = c.doFinal(plaintext.getBytes(UTF_8));
        // format: keyId : base64(iv) : base64(ciphertext+tag)
        return activeKeyId() + ":" + b64(iv) + ":" + b64(ct);
    }

    public String decrypt(String stored) throws GeneralSecurityException {
        String[] p = stored.split(":");
        Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
        c.init(Cipher.DECRYPT_MODE, keyFor(p[0]), new GCMParameterSpec(TAG_BITS, unb64(p[1])));
        c.updateAAD(p[0].getBytes());
        return new String(c.doFinal(unb64(p[2])), UTF_8);    // throws AEADBadTagException if tampered
    }
}

In your projects

IR3D (Kontentt)mfa/infrastructure/TotpSecretCipher.java · socialaccount OAuthTokenCipher

"AES/GCM/NoPadding" with a rotatable key ring, applied to TOTP secrets and linked social-account tokens (TikTok, YouTube and others). If someone leaked the DB alone, they couldn’t generate MFA codes or call those platforms as your users.

SperoTek (in dev)shared/crypto/KeyRingCipher.java · notification DefaultEmailOutbox

AES-256-GCM with key ring APP_CRYPTO_KEY_V1. A particularly thoughtful use is that outbox email payloads are sealed before they’re stored for async sending. Password-reset links and MFA codes sit in the DB until they’re delivered, so they’re encrypted while they wait.

The layers

Layer Protects against Your setup
TLS in transit Network sniffing HTTPS; Cloudflare Tunnel; RDS TLS
Disk / volume encryption (RDS, EBS with KMS) Stolen disks or snapshots AWS default for RDS
Transparent DB encryption / pgcrypto Some DB file access Optional
Application-level field encryption DB dumps, backups, SQL injection that reads data, curious admins IR3D, SperoTek
Client-side / end-to-end The server itself Not used (chat could be a candidate)
  • Envelope encryption with KMS. Store a data key encrypted by KMS and decrypt it once at startup, so the master key never leaves KMS.
  • Searchability. You can’t WHERE on encrypted fields. Store a blind index, an HMAC of the normalised value, for equality lookups.
  • Tokenization. Replace card numbers with tokens from a vault. That’s what Stripe and Paystack do for you, which is why you never handle raw card data (PCI-DSS scope).
  • Java’s SecureRandom for keys and IVs. Generate keys with KeyGenerator.getInstance("AES").init(256), and store them base64-encoded in secrets.

Check yourself

1. TOTP seeds should be…
2. What does the GCM authentication tag give you?
3. Worst GCM mistake?