Generic Secret Assignment in Code Regex for Java
/(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\s]*[:=][\s]*)["']([^"'\s]{8,})["']/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching generic secret assignment in code, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// Generic Secret Assignment in Code
// ReDoS-safe | RegexVault — Security > Secrets & Config
import java.util.regex.Pattern;
public class GenericSecretAssignmentInCodeValidator {
private static final Pattern PATTERN =
Pattern.compile("(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\\s]*[:=][\\s]*)[\"\']([^\"\'\\s]{8,})[\"\']");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("password = 'mySecretPassword123'")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
password = 'mySecretPassword123' | password = '' |
api_key = "AIzaSyD-9tSrke72I6e0qOZV" | api_key = variable_name |
token: 'eyJhbGciOiJIUzI1NiJ9' | // password might be here |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Effective secret scanning requires both pattern matching AND entropy analysis. Simple dictionary words that match the pattern are likely placeholders. Tools like TruffleHog and GitLeaks combine regex with Shannon entropy scoring.
Technical Notes
Detection pattern for secret scanning in codebases and config files. The value capture group (1) should be examined for entropy and length. False positive rate is non-trivial — values like 'your_password_here' or 'changeme' are common placeholders. Use entropy scoring alongside pattern matching.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern