Repository navigation
Description
Affects PMD Version: 7.26.0
Rule:
HardCodedCryptoKey
https://docs.pmd-code.org/latest/pmd_rules_java_security.html#hardcodedcryptokey
Description:
HardCodedCryptoKey can detect hard-coded cryptographic keys that appear directly as string literals. For example, when a string literal is passed directly to the constructor of SecretKeySpec, the rule can report a violation. However, when a semantically equivalent hard-coded string is constructed via new String(char[]), the rule does not report a violation.
The following test case demonstrates this behavior. In the first example, the key is constructed directly from a string literal, whereas the second example constructs the same string from an array of character literals. When running PMD 7.26.0 on both test cases, the first case is reported by HardCodedCryptoKey, while the second case is not. In the second case, the value of the string is still completely determined by character literals in the source code. Therefore, it could also be considered a hard-coded cryptographic key.
Code Sample demonstrating the issue:
// Direct string literal
package com.example;
import javax.crypto.spec.SecretKeySpec;
public class BadCase {
public static void main(String[]args) {
// Direct StringLiteral as first argument
SecretKeySpec keySpec= new SecretKeySpec("hardcodedKey".getBytes(),"AES");// [REPORTED LINE]
}
}
// Semantically equivalent hard-coded string constructed from character literals
package com.example;
import javax.crypto.spec.SecretKeySpec;
public class BadCase_Var {
public static void main(String[] args) {
String key = new String(new char[] {'h', 'a', 'r', 'd', 'c', 'o', 'd', 'e', 'd', 'K', 'e', 'y'});
byte[] bytes = key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");// [should be flagged]
}
}Expected outcome:
PMD could also report a HardCodedCryptoKey violation for the second case, because the cryptographic key is still statically determined by character literals in the source code. The rule could recognize semantically constant strings constructed through forms such as new String(new char[]{...}), rather than relying only on direct string literal expressions. A possible improvement would be to extend the handling of constructor calls such as new String(...) and evaluate character-array literals when determining whether the resulting value is hard-coded.
This is a false-negative case.
Running PMD through: CLI
Activity
[-][Java] HardCodedCryptoKey: False negative when a hard-coded key is constructed via new String(char[])[/-][+][java] HardCodedCryptoKey: False negative when a hard-coded key is constructed via new String(char[])[/+]suhanrain commentedon Sep 4, 2026
I'd like to work on this issue. I'll add a regression test first and then update the rule to recognize hard-coded strings constructed from character-array literals.