cwe-321-hardcoded-crypto-key
CWE-321 Hard-coded Cryptographic Key
Description
Hard-coded Cryptographic Key
Reference: https://cwe.mitre.org/data/definitions/321.html
OWASP Category: A02:2021 – Cryptographic Failures
Vulnerable Pattern
❌ Example 1: Vulnerable Pattern
// VULNERABLE: Hardcoded encryption key
private static final String SECRET_KEY = "MySecretKey12345";
private static final byte[] IV = "InitVector123456".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(IV));
Why it's vulnerable: This pattern is vulnerable to Hard-coded Cryptographic Key
Deterministic Fix
✅ Secure Implementation: Secure Implementation
// SECURE: Generate keys securely and store externally
// Key generation (do once, store securely)
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
// Generate random IV for each encryption
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
// Load key from secure storage
@Value("${encryption.key}")
private String base64Key;
public SecretKey getKey() {
byte[] keyBytes = Base64.getDecoder().decode(base64Key);
return new SecretKeySpec(keyBytes, "AES");
}
// Use with random IV
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, getKey(), new GCMParameterSpec(128, iv));
Why it's secure: Implements proper protection against Hard-coded Cryptographic Key
Detection Pattern
Look for these patterns in your codebase:
# Find hardcoded key patterns
grep -rn "SecretKeySpec.*getBytes\|new.*Key.*\"" --include="*.java"
Remediation Steps
-
Remove hardcoded keys from source code
-
Generate keys using KeyGenerator with SecureRandom
-
Store keys in secure key management system
-
Use random IV/nonce for each encryption operation
Key Imports
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
Verification
After remediation:
-
Run SAST scanner to confirm vulnerability is resolved
-
Review all instances of the vulnerable pattern
-
Add unit tests that verify the secure implementation
-
Check for similar patterns in related code
Trigger Examples
Fix CWE-321 vulnerability
Resolve Hard-coded Cryptographic Key issue
Secure this Java code against hard-coded cryptographic key
SAST reports CWE-321
Common Vulnerable Locations
| Layer | Files | Patterns |
|---|
| Controller | *Controller.java | User input handling |
| Service | *Service.java | Business logic |
| Repository | *Repository.java | Data access |
References
Source: Generated by Java CWE Security Skills Generator Last Updated: 2026-03-07