Encryption
Introduction
Encryption protects data you need to read back later: a stored third-party token, an encrypted session, a value you hand to the browser inside a cookie. The Encrypter in @plinthjs/encryption uses AES-256-GCM, an authenticated cipher. That means a payload cannot be read without the key, and it also cannot be altered without detection. If anyone changes a single byte, decryption fails.
pnpm add @plinthjs/encryptionThe package has no native dependencies. It is built on node:crypto. Passwords are a different problem: you never need to read them back, so they use a one-way hash. See Hashing for that.
Keys
An Encrypter needs a 32-byte key. Generate one with generateKeyBase64(), which returns a string prefixed with base64: that is safe to paste into an environment file:
import { Encrypter } from '@plinthjs/encryption'
const key = Encrypter.generateKeyBase64()
// => 'base64:Zk3...=' (51 characters)Store the key outside your source code, for example as APP_KEY in your .env file. The generated application ships a key:generate console command that writes a fresh APP_KEY into .env, reads it through config/app.ts, and refuses to serve in production when the key is empty. See Console and Configuration.
The constructor accepts the key in three forms:
new Encrypter(key) // 'base64:...' string
new Encrypter('0123456789abcdef0123456789abcdef') // a 32-character UTF-8 string
new Encrypter(Buffer.from(rawThirtyTwoBytes)) // a raw BufferAny other length throws an InvalidKeyError (Encryption key must be 32 bytes for AES-256-GCM.). To check a key without constructing an encrypter, use Encrypter.supported(key), which returns a boolean. Encrypter.generateKey() gives you the raw 32-byte Buffer if you prefer to encode it yourself.
WARNING
Anyone who has the key can decrypt your data and forge payloads. Keep it out of version control, never log it, and use a different key for each environment.
Encrypting and decrypting values
encrypt() serializes any JSON-safe value, encrypts it, and returns a single string. decrypt() reverses it and gives the original value back:
const encrypter = new Encrypter(key)
const payload = encrypter.encrypt({ id: 1, tags: ['a', 'b'] })
// => an opaque base64 string
encrypter.decrypt<{ id: number; tags: string[] }>(payload)
// => { id: 1, tags: ['a', 'b'] }Each call uses a fresh random initialization vector, so encrypting the same value twice gives different strings. Both decrypt to the same value.
To work with raw strings without the JSON step, use encryptString() and decryptString():
const token = encrypter.encryptString('hello')
encrypter.decryptString(token) // => 'hello'Use the string variants for values that are already strings (like an access token). They store the text as is, where encrypt() would add JSON quotes first. A payload made with encrypt() must be read with decrypt(), and one made with encryptString() with decryptString().
The returned payload is a base64 envelope holding the IV, the authentication tag, and the ciphertext, so it is safe to put in a database column, a cookie, or a URL after encoding.
Handling failures
Decryption throws a DecryptionError when the payload is malformed, was encrypted with a different key, or was tampered with:
import { DecryptionError } from '@plinthjs/encryption'
try {
encrypter.decrypt(payloadFromUser)
} catch (error) {
if (error instanceof DecryptionError) {
// treat as an invalid or forged value, for example respond with 400
}
}The error message never says why decryption failed. That is deliberate: distinguishing "wrong key" from "tampered" would help an attacker.
Rotating keys
Changing your key would make every stored payload unreadable. Key rotation avoids that. Keep the old key as a previous key: new data is encrypted with the current key, and decrypt() and decryptString() fall back to each previous key, in order, when the current one fails:
const current = Encrypter.generateKeyBase64()
const old = process.env['OLD_KEY'] ?? ''
const encrypter = new Encrypter(current, [old])
encrypter.decrypt(payloadEncryptedWithOldKey) // works, via the previous key
encrypter.encrypt('new data') // always uses the current keywithPreviousKeys(keys) returns a new encrypter with the same current key and a different list of previous keys, and getAllKeys() returns the current key followed by the previous ones. The generated application reads a comma-separated APP_PREVIOUS_KEYS variable into previousKeys in its app config for exactly this.
A rotation looks like this:
- Generate a new key. Make it
APP_KEYand move the old key intoAPP_PREVIOUS_KEYS. - Deploy. Old payloads still decrypt, and everything written from now on uses the new key.
- Once you have re-encrypted old data (or it has expired), remove the old key from the list.
Every previous key must also be valid. An invalid one throws InvalidKeyError when you build the encrypter.
Comparing secrets safely
When you compare tokens or signatures, a normal === can leak timing information. Encrypter.hashEquals(a, b) compares two strings in constant time and returns false for strings of different length:
Encrypter.hashEquals('abc', 'abc') // => true
Encrypter.hashEquals('abc', 'abd') // => falseUsing the encrypter with sessions
An Encrypter satisfies the seam @plinthjs/session uses to encrypt stored sessions, so you can wrap any session store with it:
import { ArraySessionStore, encryptedSession } from '@plinthjs/session'
const { manager } = encryptedSession(new ArraySessionStore(), encrypter)See Session for the available stores.
Related
- Hashing for one-way password hashing.
- Configuration for where the application key lives.