Encryption Key Hardcoded in Application Source
What Is This Vulnerability?
An encryption key or initialization vector used for encrypting sensitive data (such as user PII, payment information, or session data) is written directly in the source code. Anyone with access to the codebase can decrypt all data that was encrypted with this key, rendering the encryption completely useless.
Why It Happens
Encryption libraries require a key parameter, and developers often define a constant string in code for simplicity. Some teams copy encryption examples from Stack Overflow or documentation that use placeholder keys and never replace them with properly managed secrets. Key management is perceived as complex, leading to shortcuts.
Example Code
import crypto from "crypto";
const ENCRYPTION_KEY = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6";
const IV = "1234567890abcdef";
export function encrypt(text: string): string {
const cipher = crypto.createCipheriv("aes-256-cbc", ENCRYPTION_KEY, IV);
let encrypted = cipher.update(text, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
}import crypto from "crypto";
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;
export function encrypt(text: string): string {
if (!ENCRYPTION_KEY) {
throw new Error("ENCRYPTION_KEY environment variable is required");
}
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-cbc", Buffer.from(ENCRYPTION_KEY, "hex"), iv);
let encrypted = cipher.update(text, "utf8", "hex");
encrypted += cipher.final("hex");
return iv.toString("hex") + ":" + encrypted;
}How Hackers Exploit It
Once an attacker has the encryption key, they can decrypt any data that was protected with it. This includes data at rest in databases, data in transit if custom encryption was used, and any backups or exports. A static IV (initialization vector) makes the problem worse, as identical plaintext always produces identical ciphertext, enabling pattern analysis.
How to Fix It
Store encryption keys in environment variables or a dedicated key management service (AWS KMS, Google Cloud KMS, Azure Key Vault). Always generate a random IV for each encryption operation and prepend it to the ciphertext. Use authenticated encryption modes like AES-256-GCM. Implement key rotation so that compromised keys affect only a subset of data.