When this skill is activated, always start your first response with the 🧢 emoji.
Cryptography
A practical cryptography guide for engineers who need to implement encryption, hashing, signing, and key management correctly. This skill covers the seven most common cryptographic tasks with production-ready TypeScript/Node.js code, opinionated algorithm choices, and a clear anti-patterns table. Designed for engineers who understand the basics but need confident, safe defaults.
When to use this skill
Trigger this skill when the user:
- Hashes or stores passwords (bcrypt, argon2, any hashing question)
- Encrypts or decrypts data at rest or in transit (AES, RSA, envelope encryption)
- Implements JWT signing, verification, or refresh token flows
- Configures TLS certificates on servers, proxies, or mutual TLS
- Implements HMAC signatures for webhooks or API request signing
- Designs or implements a key rotation strategy
- Generates cryptographically secure random tokens, IDs, or salts
- Chooses between symmetric vs asymmetric, hashing vs encryption, or any algorithm
Do NOT trigger this skill for:
- General security posture or authentication/authorization flows - use the backend-engineering security reference instead
- Building a custom cryptographic algorithm, cipher, or protocol - that is always wrong; redirect the user immediately
Key principles
-
Never invent your own crypto primitives - Do not implement block ciphers, hash functions, key derivation, or signature schemes. The gap between "looks correct" and "is correct" is where attackers live. Use audited libraries (Node.js
crypto,bcrypt,jose,argon2) that encode decades of research. -
Use the highest-level API available - If a library has a
hashPassword()function, use it over constructing the primitive manually. High-level APIs embed safe defaults. Low-level APIs require you to know every parameter that matters. -
Rotate keys regularly and plan for it upfront - Key rotation is not an afterthought. Envelope encryption makes rotation cheap: re-encrypt only the data key, not the data. Design systems with rotation in mind before writing the first line of code.
-
Hash passwords with bcrypt or argon2 - never MD5 or SHA* - MD5 and SHA-family hashes are fast by design. Fast hashes mean fast brute force. Password hashing needs to be slow. Argon2id is the current standard. bcrypt with cost 12+ is the safe fallback.
-
TLS 1.3 is the minimum - Disable TLS 1.0 and 1.1 everywhere. They have known attacks (BEAST, POODLE). TLS 1.2 is acceptable only as a fallback for legacy clients. TLS 1.3 removes the broken cipher suites entirely and has mandatory forward secrecy.
Core concepts
Symmetric vs asymmetric encryption - Symmetric uses one key for both encrypt and decrypt (AES). Fast, suitable for bulk data. The hard problem is securely sharing the key. Asymmetric uses a key pair: public key encrypts, private key decrypts (RSA, ECDH). Slower, but solves the key distribution problem. In practice, use asymmetric to exchange a symmetric key, then use symmetric for the actual data (this is what TLS does).
Hashing vs encryption - Hashing is one-way: you can verify but not reverse. Encryption is two-way: you can recover the original with the key. Use hashing for passwords (you verify, never recover). Use encryption for data you need to read back (PII, configuration secrets).
Digital signatures - Asymmetric operation where the private key signs and the public key verifies. Proves authenticity (this came from the private key holder) and integrity (data was not modified). Used in JWTs (RS256, ES256), code signing, and document verification.
Key derivation functions (KDF) - Transform a low-entropy input (password) into a high-entropy key using a slow, memory-hard algorithm. PBKDF2, bcrypt, scrypt, and Argon2 are KDFs. Do not use raw SHA-256 to derive a key from a password.
Envelope encryption - The pattern for production key management. Encrypt data with a data encryption key (DEK). Encrypt the DEK with a key encryption key (KEK) stored in a KMS. Store the encrypted DEK alongside the ciphertext. To rotate: ask KMS to re-wrap the DEK with the new KEK. The data itself never needs re-encryption.
Common tasks
Hash passwords with bcrypt / argon2
Use argon2 (preferred) or bcrypt (widely supported). Never use crypto.createHash
for passwords.
import argon2 from 'argon2';
// Hash a password
export async function hashPassword(password: string): Promise<string> {
return argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3,
parallelism: 1,
});
}
// Verify a password
export async function verifyPassword(hash: string, password: string): Promise<boolean> {
return argon2.verify(hash, password);
}
// bcrypt fallback (cost 12+ required in production)
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, SALT_ROUNDS);
}
export async function verifyPassword(hash: string, password: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
Always use
argon2.verify/bcrypt.comparefor comparison - they are constant-time. Never use===to compare hashes.
Encrypt data with AES-256-GCM
AES-256-GCM is authenticated encryption: it provides both confidentiality and integrity. Always use GCM mode, not CBC (CBC requires a separate MAC and is error-prone).
import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';
const ALGORITHM = 'aes-256-gcm';
const KEY_LENGTH = 32; // 256 bits
const IV_LENGTH = 12; // 96 bits - recommended for GCM
const TAG_LENGTH = 16; // 128 bits
export function encrypt(plaintext: string, key: Buffer): {
ciphertext: string;
iv: string;
tag: string;
} {
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_LENGTH });
const encrypted = Buffer.concat([
cipher.update(plaintext, 'utf8'),
cipher.final(),
]);
return {
ciphertext: encrypted.toString('base64'),
iv: iv.toString('base64'),
tag: cipher.getAuthTag().toString('base64'),
};
}
export function decrypt(
ciphertext: string,
iv: string,
tag: string,
key: Buffer
): string {
const decipher = createDecipheriv(
ALGORITHM,
key,
Buffer.from(iv, 'base64'),
{ authTagLength: TAG_LENGTH }
);
decipher.setAuthTag(Buffer.from(tag, 'base64'));
return Buffer.concat([
decipher.update(Buffer.from(ciphertext, 'base64')),
decipher.final(),
]).toString('utf8');
}
// Generate a key (store in KMS, never hardcode)
export function generateKey(): Buffer {
return randomBytes(KEY_LENGTH);
}
Never reuse an IV with the same key. Generate a fresh random IV for every encryption operation and store it alongside the ciphertext.
Implement JWT signing and verification
Use the jose library. It enforces algorithm allowlisting, handles key rotation via
JWKS, and is actively maintained.
import { SignJWT, jwtVerify, generateKeyPair } from 'jose';
// Generate a key pair once (store private key in secrets manager)
export async function generateJwtKeys() {
return generateKeyPair('ES256'); // prefer ES256 over RS256 - smaller, faster
}
// Sign a JWT
export async function signToken(
payload: Record<string, unknown>,
privateKey: CryptoKey
): Promise<string> {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'ES256' })
.setIssuedAt()
.setExpirationTime('15m') // short-lived access tokens
.setIssuer('https://your-api.example.com')
.setAudience('https://your-api.example.com')
.sign(privateKey);
}
// Verify a JWT
export async function verifyToken(
token: string,
publicKey: CryptoKey
): Promi