Secure Key Generation for Encryption

Learn how to generate cryptographically secure encryption keys. Covers random key generation, key derivation from passwords (PBKDF2), key sizes, and common mistakes to avoid in key management.

Modes & Padding

Detailed Explanation

Secure Key Generation for Encryption

The security of any encryption system depends entirely on the quality of the key. A mathematically perfect algorithm with a weak key provides no security. Understanding proper key generation is foundational to cryptographic practice.

Random Key Generation

The gold standard for key generation is cryptographically secure random number generation:

// Web Crypto API — the correct approach
const key = await crypto.subtle.generateKey(
  { name: "AES-GCM", length: 256 },
  true,
  ["encrypt", "decrypt"]
);

// Or generate raw random bytes
const keyBytes = crypto.getRandomValues(new Uint8Array(32)); // 256 bits

Never use Math.random() for key generation — it is not cryptographically secure and its output can be predicted.

Key Derivation from Passwords

Passwords are poor encryption keys — they have low entropy (typically 20-40 bits vs 128-256 bits for proper keys). Key Derivation Functions (KDFs) stretch passwords into full-length keys:

PBKDF2:

const salt = crypto.getRandomValues(new Uint8Array(16));
const keyMaterial = await crypto.subtle.importKey(
  "raw",
  new TextEncoder().encode(password),
  "PBKDF2", false, ["deriveKey"]
);

const key = await crypto.subtle.deriveKey(
  { name: "PBKDF2", salt, iterations: 600000, hash: "SHA-256" },
  keyMaterial,
  { name: "AES-GCM", length: 256 },
  true, ["encrypt", "decrypt"]
);

The iteration count is critical — higher values make brute-force attacks slower. OWASP recommends at least 600,000 iterations for PBKDF2-SHA256 as of 2023.

Key Sizes and Entropy

Key Size Entropy Brute Force (1T keys/sec)
64 bits Low ~5 hours
128 bits High ~10^25 years
256 bits Very High ~10^51 years

A 128-bit key has enough entropy to resist brute force for the foreseeable future. 256-bit keys add a margin for quantum computing threats.

Common Key Generation Mistakes

  1. Using Math.random() — Predictable, not suitable for cryptography
  2. Deriving keys from short passwords without a KDF — Vulnerable to dictionary attacks
  3. Hardcoding keys in source code — Keys in code end up in version control, logs, and backups
  4. Using the same key for multiple purposes — One key for encryption, a different key for authentication
  5. Insufficient PBKDF2 iterations — Using 1000 iterations when 600,000 is recommended
  6. Reusing salts — Each password should have a unique salt

Key Storage Considerations

  • Browser: Use crypto.subtle.generateKey() with extractable: false to prevent JavaScript from reading the raw key bytes
  • Server: Store keys in hardware security modules (HSMs) or dedicated key management services (KMS)
  • Mobile: Use the platform keystore (Android Keystore, iOS Keychain)
  • Environment variables: Better than hardcoded, but still accessible to any process in the environment

Use Case

Secure key generation is relevant every time a developer implements encryption. Password-based encryption for user data (file encryption tools, password managers, encrypted notes) requires proper KDF usage. Server-side encryption for databases or object storage requires random key generation and rotation policies. Understanding key generation pitfalls prevents the most common class of real-world encryption failures.

Try It — Encryption Playground

Open full tool