Skip to main content

Code reviews rule: Hardcoded encryption keys

Written by David Martin

Hardcoded encryption keys

Why is this an issue?

Hardcoding encryption keys in source code is not secure and most security audits will flag this as a critical vulnerability. Having keys in code means they are visible to anyone with code access, compromising them unless they are rotated frequently.

Examples

Example of incorrect code:

Blob key = Blob.valueOf('0123456789abcdef'); // String literal containing hardcoded key 
Blob encrypted = Crypto.encryptWithManagedIV('AES256', key, data);

Example of correct code:

Blob key = Crypto.generateAesKey(256); // Generate a random key at runtime
Blob encrypted = Crypto.encryptWithManagedIV('AES256', key, data);

How can I fix violations?

Generate random keys: Use Crypto.generateAesKey() to create secure keys.

Resources

Did this answer your question?