Table of Contents
1. Why char[] is Safer for Passwords
The Problem with String
- Immutability:
String
values remain in memory until garbage-collected, risking exposure in memory dumps. - Logging Risks: Accidentally logging passwords (e.g.,
System.out.println(password)
).
Solution: Use char[]
char[] password = passwordField.getPassword();
// Wipe the array after use to minimize exposure
Arrays.fill(password, '\0');
Best Practices:
- Never Store Passwords as
String
: Usechar[]
or specialized classes likeSecureString
. - Avoid
String
in Logs: Mask sensitive data in debug outputs. - Use
JPasswordField
in Swing: Returnschar[]
by default.
2. Preventing SQL Injection
The Danger of String Concatenation
// 🚨 Vulnerable code!
String query = "SELECT * FROM users WHERE name = '" + userInput + "'";
A malicious userInput
like ' OR '1'='1
can bypass authentication.
Solution: Parameterized Queries
Use PreparedStatement
to separate SQL logic from data:
String query = "SELECT * FROM users WHERE name = ?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, userInput); // Automatically escapes input
ResultSet rs = stmt.executeQuery();
}
Key Benefits:
- Escapes special characters (e.g.,
'
,"
). - Prevents malicious SQL execution.
For ORM Users: Frameworks like Hibernate/JPA also use parameterization internally.
3. Validating and Sanitizing User Input
Input Validation Rules
- Whitelist Valid Characters: Reject anything outside expected patterns.
- Use Regex for Format Checks:
if (!email.matches("^[\\w.-]+@[\\w.-]+\\.\\w+$")) {
throw new InvalidInputException("Invalid email");
}
Sanitization Techniques
- Escape HTML/JavaScript: Prevent XSS attacks in web apps.
String safeOutput = Encode.forHtml(userInput); // OWASP Java Encoder
- Limit Input Length:
if (userInput.length() > MAX_LENGTH) {
throw new InputTooLongException();
}
Common Security Mistakes
❌ Storing Secrets in String
:
String apiKey = "sk_live_12345"; // Visible in memory dumps!
❌ Trusting Input from Untrusted Sources:
String filename = userInput + ".txt";
Files.write(Path.of(filename), data); // Path traversal risk!
❌ Logging Sensitive Data:
logger.info("User password reset: " + password); // Exposed in logs!
Best Practices
- Use
char[]
for Passwords: Wipe it immediately after use. - Parameterize All Queries: Never concatenate SQL.
- Validate Before Processing: Assume all input is malicious.
- Sanitize for Context: HTML, SQL, OS commands, etc.
- Leverage Security Libraries:
FAQ
Why is char[]
safer than String
if both reside in memory?
char[]
allows manual overwriting, reducing the time sensitive data is exposed.
Are parameterized queries enough to prevent SQL injection?
Yes, when used correctly. Avoid dynamic SQL with Statement
/string concatenation.
How to sanitize file paths in Java?
Use Path.of()
with validation:
if (!userInput.matches("[a-zA-Z0-9_-]+")) {
throw new InvalidFilenameException();
}