| name | cwe-321-hardcoded-crypto-key |
| description | Use this skill when you need to remediate CWE-321 (Hard-coded Cryptographic Key) vulnerabilities in Java code. Triggers on SAST findings, security reviews, or when fixing hard-coded cryptographic key issues. |
| version | 1.0.0 |
| license | MIT |
| tags | ["security","java","cwe-321","remediation","sast","cryptography","hardcoded-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
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
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
@Value("${encryption.key}")
private String base64Key;
public SecretKey getKey() {
byte[] keyBytes = Base64.getDecoder().decode(base64Key);
return new SecretKeySpec(keyBytes, "AES");
}
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:
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
| 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