Generar cryptographically secure session keys
Session claves debe ser unpredictable y único per session. Aprender a generar them usando un CSPRNG y derive sub-claves con HKDF.
- 1
A session key is a fresh symmetric key generated for a single session. It must come from a CSPRNG (cryptographically secure pseudorandom number generator) — never Math.random(). For TLS, the session key is derived via ECDHE; for application-level, generate 256 random bits.
- 2 Generador de bytes aleatorios →
Generar 32 bytes (256 bits) of cryptographically secure random data. This is your session key. Use the Web Crypto API (crypto.getRandomValues) or Node.js crypto.randomBytes — never Math.random() or Date.now().
- 3 Generador de HMAC →
Derive sub-keys from the master session key using HKDF (HMAC-based Key Derivation Function). For example, derive separate keys for encryption and MAC: K_enc = HKDF(master, "encryption"), K_mac = HKDF(master, "mac").
- 4 Cifrador AES →
Use the derived encryption key to protect session data. The key exists only in memory for the session duration and is zeroed on logout or session timeout.
- 5
For forward secrecy, generate a new ephemeral key pair per session, exchange public keys via Diffie-Hellman, and derive the session key from the shared secret. Discard the ephemeral keys after the session — past sessions cannot be decrypted even if long-term keys are compromised.
Preguntas frecuentes
- Why not use Math.random()?
- Math.random() is not cryptographically secure — its output is predictable with enough observations. It uses a PRNG (not CSPRNG) that can be reverse-engineered. Always use crypto.getRandomValues() (browser) or crypto.randomBytes() (Node.js).
- What is HKDF and why use it?
- HKDF (RFC 5869) expands a master key into multiple independent sub-keys using HMAC. It ensures that compromising one sub-key does not reveal others. Use it to derive separate keys for encryption, authentication, and IV generation from a single master key.