overview
sidebar_position: 0 pagination_prev: null ai_summary: "Encrypt class provides symmetric encryption (AES-GCM algorithms: aes-256-gcm, aes-192-gcm, aes-128-gcm). Keys must be base64-encoded with specific bit lengths. Use Encrypt.generateKey() to generate keys. Never hard-code keys - use environment variables or AWS SecretsManager."
Overview
A light-weight Encrypt class is provided by Dream, which can be freely utilized throughout your app for symmetric encryption tasks.
Algorithms
By default, the Encrypt class only supports AES-GCM algorithms (meaning aes-256-gcm, aes-192-gcm, and aes-128-gcm), since the gcm is considered to be the most widely-used and secure modern encryption standard.
Provide the algorithm you wish to use as the second argument to .encrypt or .decrypt, like so:
const encrypted = Encrypt.encrypt('helloworld', {
algorithm: 'aes-256-gcm',
key: AppEnv.string('APP_ENCRYPTION_KEY'),
})
const decrypted = Encrypt.decrypt(encrypted, {
algorithm: 'aes-256-gcm',
key: AppEnv.string('APP_ENCRYPTION_KEY'),
})
console.log(decrypted)
// 'helloworld'
Keys
Encryption keys are an essential part of any encryption algorithm, and must be provided in specific formats to be considered valid for a given encryption algorithm. For example, for aes-256-gcm, a 32 bit encryption key must be provided in base64 encoding. The list of requirements is as follows:
aes-256-gcm: 32-bit, base64-encoded stringaes-192-gcm: 24-bit, base64-encoded stringaes-128-gcm: 16-bit, base64-encoded string
Generating keys
Luckily, Dream handles the complexity of figuring out how to generate keys for your application for you. To generate a key, simply open your console and generate them with the .generateKey method, passing the algorithm you wish to use, like so:
NODE_ENV=development pnpm console
> Encrypt.generateKey('aes-256-gcm')
// '65ogKxacRKyNxj20PCQKuBnxKgOty5eQnY4Ktbk04U0='
Do not hard-code this encryption key into your application! Always use either env vars, or, better yet, A tool like AWS SecretsManager to pull in your env vars at runtime.