Java Secure Coding
Java secure coding means writing Java programs that keep working correctly even when someone sends them hostile input or tries to misuse them. Java already removes whole classes of bugs, such as buffer overflows, but many attacks still target the logic you write yourself.
This lesson walks through the most important Java secure coding techniques one by one, each with a small runnable example: defensive copying, protecting sensitive data, failing securely, blocking path traversal, preventing integer overflow, stopping SQL injection and filtering deserialization. It builds on the overview in Java Security.
Core Java Secure Coding Principles
Most secure coding rules come from a few simple principles. Keep them in mind as you read the examples.
| Principle | Meaning | Example in Java |
|---|---|---|
| Validate input | Treat all outside data as untrusted | Allowlist regex for file names |
| Least privilege | Give code and users only the access they need | Role checks, private fields |
| Fail securely | Errors must not open access or leak details | Generic error messages |
| Defense in depth | Use more than one protective layer | Validation and path checks |
| Minimize exposure | Keep secrets out of logs and memory | Masked toString(), wiped char[] |
| Prefer immutability | Objects that cannot change cannot be tampered with | List.copyOf, records |
Defensive Copying and Immutability
If a class keeps a reference to a mutable object it received, the caller can change that object later and bypass the class's checks. A defensive copy stores a private copy instead, and an unmodifiable view stops callers from changing what you return.
import java.util.ArrayList;
import java.util.List;
public class DefensiveCopy {
// UNSAFE: stores and returns the caller's list directly
static class UnsafeCourse {
private final List<String> enrolledStudents;
UnsafeCourse(List<String> students) { this.enrolledStudents = students; }
List<String> students() { return enrolledStudents; }
}
// SAFE: copies on the way in and returns a read-only view
static class SafeCourse {
private final List<String> enrolledStudents;
SafeCourse(List<String> students) { this.enrolledStudents = List.copyOf(students); }
List<String> students() { return enrolledStudents; }
}
public static void main(String[] args) {
List<String> input = new ArrayList<>(List.of("Asha", "Ravi"));
UnsafeCourse unsafe = new UnsafeCourse(input);
SafeCourse safe = new SafeCourse(input);
input.add("Intruder"); // caller changes its own list later
unsafe.students().add("Another"); // caller changes the returned list
System.out.println("Unsafe course: " + unsafe.students());
try {
safe.students().add("Another");
} catch (UnsupportedOperationException e) {
System.out.println("Safe course refused to change");
}
System.out.println("Safe course: " + safe.students());
}
}
Output:
Unsafe course: [Asha, Ravi, Intruder, Another]
Safe course refused to change
Safe course: [Asha, Ravi]
How it works:
UnsafeCoursestores the caller'sArrayList. When the caller adds"Intruder"to its own list, the course changes too, andstudents()hands out the same list for anyone to modify.SafeCourseusesList.copyOf, which makes an immutable copy. Later changes toinputdo not reach it, andaddthrowsUnsupportedOperationException.
Note: The same rule applies to arrays and to old mutable types such as
java.util.Date. Copy them on the way in and on the way out, or use immutable types such asLocalDate.
Keeping Passwords and Secrets Out of Logs
Log files are read by many people and tools, and they are often kept for years. Never print passwords, tokens or full card numbers. Store passwords in a char[] so you can wipe them after use, because a String cannot be cleared.
import java.util.Arrays;
public class SensitiveData {
// A record prints every field by default, so override toString for secrets
record LoginRequest(String username, char[] password) {
@Override
public String toString() {
return "LoginRequest[username=" + username + ", password=****]";
}
}
static String maskCard(String cardNumber) {
String lastFour = cardNumber.substring(cardNumber.length() - 4);
return "**** **** **** " + lastFour;
}
public static void main(String[] args) {
char[] password = {'p', '@', 's', 's', '1', '2', '3'};
LoginRequest request = new LoginRequest("asha", password);
System.out.println("Log: " + request);
System.out.println("Log: card " + maskCard("4111111111111111"));
// ... use the password, then wipe it from memory
Arrays.fill(password, '\0');
System.out.println("Password chars after wipe: " + Arrays.toString(password).replace("\u0000", "0"));
}
}
Output:
Log: LoginRequest[username=asha, password=****]
Log: card **** **** **** 1111
Password chars after wipe: [0, 0, 0, 0, 0, 0, 0]
How it works:
- A record's generated
toString()prints every component. The override replaces the password with****, so logging the whole request is safe. maskCardkeeps only the last four digits, which is enough for a support team to identify a card.Arrays.fill(password, '\0')overwrites every character. AStringwould stay in memory until the garbage collector removes it, and you cannot control when that happens.
Failing Securely Without Leaking Details
When something goes wrong, the user should get a short generic message, while the full technical details go to a server log. Stack traces and exception messages can reveal class names, SQL, file paths or which accounts exist.
import java.util.Map;
import java.util.UUID;
public class FailSecurely {
private static final Map<String, Integer> BALANCES = Map.of("ACC-1", 5000);
static String withdraw(String accountId, int amount) {
try {
int balance = BALANCES.get(accountId); // throws NullPointerException for unknown ids
if (amount > balance) {
return "Declined: insufficient funds";
}
return "Approved: " + amount;
} catch (RuntimeException e) {
// Internal details go to the server log with a reference id...
String errorId = UUID.randomUUID().toString().substring(0, 8);
System.out.println(" [server log] error " + errorId + ": " + e);
// ...the user only sees a generic message and the same id
return "Request failed. Reference: " + errorId;
}
}
public static void main(String[] args) {
System.out.println(withdraw("ACC-1", 1000));
System.out.println(withdraw("ACC-1", 9000));
System.out.println(withdraw("ACC-404", 100));
}
}
Output (the reference id changes on every run):
Approved: 1000
Declined: insufficient funds
[server log] error 80178408: java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
Request failed. Reference: 80178408
How it works:
- An unknown account makes
BALANCES.getreturnnull, and unboxing it throwsNullPointerException. - The
catchblock logs the real exception together with a short random reference id. - The caller only sees
Request failedand the id. A support team can match the id to the log entry, but an attacker learns nothing about the code.
Note: Notice that the method returns a failure in the error path. Code such as
catch (Exception e) { return true; }in an access check would "fail open" and let everyone in.
Preventing Path Traversal in Java
If a user can choose a file name, they may send ../../etc/passwd to escape the folder you meant to serve. Resolve the name against a fixed base folder, normalize() the result, and confirm it still starts with the base folder.
import java.nio.file.Path;
public class PathTraversal {
private static final Path UPLOAD_DIR = Path.of("/srv/app/uploads").toAbsolutePath().normalize();
static Path resolveSafely(String userFileName) {
Path requested = UPLOAD_DIR.resolve(userFileName).normalize();
if (!requested.startsWith(UPLOAD_DIR)) {
throw new SecurityException("Path escapes upload folder: " + userFileName);
}
return requested;
}
public static void main(String[] args) {
String[] fileNames = {"notes.pdf", "reports/2026.csv", "../../../etc/passwd", "/etc/shadow"};
for (String fileName : fileNames) {
try {
System.out.println("OK " + resolveSafely(fileName));
} catch (SecurityException e) {
System.out.println("BLOCKED " + e.getMessage());
}
}
}
}
Output:
OK /srv/app/uploads/notes.pdf
OK /srv/app/uploads/reports/2026.csv
BLOCKED Path escapes upload folder: ../../../etc/passwd
BLOCKED Path escapes upload folder: /etc/shadow
How it works:
resolvejoins the base folder and the user's name.normalize()removes.and..parts, so../../../etc/passwdbecomes/etc/passwd.startsWith(UPLOAD_DIR)compares whole path elements, not just characters, so a folder nameduploads-oldwould not pass by accident.- An absolute name such as
/etc/shadowreplaces the base folder completely when resolved, and the same check catches it.
Preventing Integer Overflow
Java int arithmetic wraps around silently when a result is too large. In price, quantity or size calculations, a wrapped negative number can turn a huge order into a refund. Math.addExact, Math.multiplyExact and their friends throw an exception instead.
public class OverflowCheck {
public static void main(String[] args) {
int pricePerItem = 1_500_000;
int quantity = 2_000;
// Plain multiplication silently wraps around to a negative number
int unsafeTotal = pricePerItem * quantity;
System.out.println("Unsafe total: " + unsafeTotal);
// multiplyExact throws instead of returning a wrong value
try {
int safeTotal = Math.multiplyExact(pricePerItem, quantity);
System.out.println("Safe total: " + safeTotal);
} catch (ArithmeticException e) {
System.out.println("Rejected: " + e.getMessage());
}
// Use a wider type when large values are expected
long correctTotal = Math.multiplyExact((long) pricePerItem, quantity);
System.out.println("Correct total (long): " + correctTotal);
}
}
Output:
Unsafe total: -1294967296
Rejected: integer overflow
Correct total (long): 3000000000
How it works:
1,500,000 × 2,000is 3 billion, which is larger thanInteger.MAX_VALUE(2,147,483,647). The plain*wraps to a negative number without any warning.Math.multiplyExactdetects the overflow and throwsArithmeticException, so the bad value never reaches the rest of the program.- Casting one operand to
longselects thelongversion ofmultiplyExact, which has enough range for the real total.
Preventing SQL Injection in Java
SQL injection happens when user input is glued into a SQL string. The input can then close the quoted value and add its own SQL. This example only builds the query strings, so you can see what the database would receive.
public class SqlInjectionDemo {
static String buildQueryUnsafely(String username) {
return "SELECT * FROM users WHERE username = '" + username + "'";
}
public static void main(String[] args) {
System.out.println(buildQueryUnsafely("asha"));
System.out.println(buildQueryUnsafely("' OR '1'='1"));
System.out.println(buildQueryUnsafely("x'; DROP TABLE users; --"));
}
}
Output:
SELECT * FROM users WHERE username = 'asha'
SELECT * FROM users WHERE username = '' OR '1'='1'
SELECT * FROM users WHERE username = 'x'; DROP TABLE users; --'
How it works:
- With a normal name, the query looks fine.
- The input
' OR '1'='1closes the quote and adds a condition that is always true, so the query would return every user. - The third input ends the statement and adds a
DROP TABLEcommand.
The fix is to send the SQL and the values separately with a PreparedStatement, as covered in Java PreparedStatement:
String sql = "SELECT id, username FROM users WHERE username = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, username); // sent as data, never parsed as SQL
try (ResultSet rows = statement.executeQuery()) {
// read the rows
}
}
The ? placeholder is fixed in the query before the value arrives. Whatever the user types, the database treats it as one string value, so ' OR '1'='1 simply finds no user with that strange name.
Filtering Java Deserialization
Reading objects with ObjectInputStream from an untrusted source is dangerous, because the stream chooses which classes get created. Attackers use this to run code through "gadget" classes in your class path. Since Java 9, an ObjectInputFilter lets you allow only the classes you expect.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
public class DeserializationFilter {
record Student(String name, int marks) implements Serializable { }
static byte[] serialize(Object value) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(value);
}
return bytes.toByteArray();
}
static Object readWithFilter(byte[] data) throws Exception {
// Allow only our Student record and java.lang classes; reject everything else
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"DeserializationFilter$Student;java.lang.*;maxdepth=5;!*");
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
in.setObjectInputFilter(filter);
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
System.out.println("Read: " + readWithFilter(serialize(new Student("Asha", 91))));
try {
readWithFilter(serialize(new HashMap<>()));
} catch (InvalidClassException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Output:
Read: Student[name=Asha, marks=91]
Rejected: filter status: REJECTED
How it works:
- The filter pattern is read left to right.
DeserializationFilter$Studentandjava.lang.*are allowed,maxdepth=5limits nesting, and the final!*rejects every other class. - The
Studentrecord passes the filter and is read normally. - A
HashMapis not on the list, soreadObjectthrowsInvalidClassExceptionwith the statusREJECTEDbefore the object is built.
Note: The safest option is to avoid Java serialization for untrusted data and use a plain data format such as JSON with a fixed schema. Use a filter when you must read serialized objects.
Real-World Example: A Secure File Download Service
This service lets students and teachers download course files. It combines several Java secure coding techniques: role checks, allowlist validation, a path traversal check as a second layer, a file size limit, generic error responses and log lines that cannot be forged.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.regex.Pattern;
public class SecureDownloadService {
private static final Pattern SAFE_NAME = Pattern.compile("[A-Za-z0-9_-]{1,40}\\.(pdf|txt|csv)");
private static final Set<String> ALLOWED_ROLES = Set.of("student", "teacher");
private static final long MAX_BYTES = 1_000;
private final Path baseDir;
SecureDownloadService(Path baseDir) {
this.baseDir = baseDir.toAbsolutePath().normalize();
}
String download(String role, String fileName) {
// 1. Least privilege: only known roles may download
if (role == null || !ALLOWED_ROLES.contains(role)) {
return deny("role not allowed", role, fileName);
}
// 2. Allowlist validation of the file name
if (fileName == null || !SAFE_NAME.matcher(fileName).matches()) {
return deny("invalid file name", role, fileName);
}
// 3. Path check as a second layer (defense in depth)
Path target = baseDir.resolve(fileName).normalize();
if (!target.startsWith(baseDir)) {
return deny("path traversal", role, fileName);
}
// 4. Resource limits and secure failure
try {
if (Files.size(target) > MAX_BYTES) {
return deny("file too large", role, fileName);
}
return "200 OK: " + Files.readString(target).trim();
} catch (IOException e) {
System.out.println(" [log] I/O problem for " + fileName + ": " + e.getClass().getSimpleName());
return "404 Not Found";
}
}
private String deny(String reason, String role, String fileName) {
// Log the real reason for admins; quote untrusted input so it cannot fake log lines
String safeLogName = String.valueOf(fileName).replaceAll("[\\r\\n]", "_");
System.out.println(" [log] denied (" + reason + ") role=" + role + " file=\"" + safeLogName + "\"");
return "403 Forbidden";
}
public static void main(String[] args) throws IOException {
Path folder = Files.createTempDirectory("course-files");
Files.writeString(folder.resolve("syllabus.pdf"), "Java Security syllabus");
Files.writeString(folder.resolve("big.csv"), "x".repeat(5_000));
SecureDownloadService service = new SecureDownloadService(folder);
System.out.println(service.download("student", "syllabus.pdf"));
System.out.println(service.download("guest", "syllabus.pdf"));
System.out.println(service.download("student", "../../etc/passwd"));
System.out.println(service.download("teacher", "big.csv"));
System.out.println(service.download("teacher", "missing.txt"));
System.out.println(service.download("student", "a.txt\n[log] admin login OK"));
}
}
Output:
200 OK: Java Security syllabus
[log] denied (role not allowed) role=guest file="syllabus.pdf"
403 Forbidden
[log] denied (invalid file name) role=student file="../../etc/passwd"
403 Forbidden
[log] denied (file too large) role=teacher file="big.csv"
403 Forbidden
[log] I/O problem for missing.txt: NoSuchFileException
404 Not Found
[log] denied (invalid file name) role=student file="a.txt_[log] admin login OK"
403 Forbidden
How it works:
- Least privilege. Only the roles in
ALLOWED_ROLESmay download. Aguestgets403 Forbidden. - Allowlist validation.
SAFE_NAMEaccepts only letters, digits,_and-, followed by.pdf,.txtor.csv. Any/,..or newline makes the name invalid, as explained further in Java Input Validation. - Defense in depth. The
normalize()andstartsWithcheck would still stop path traversal if someone later relaxed the regex. - Resource limits.
big.csvis larger thanMAX_BYTES, so the service refuses it instead of loading a huge file into memory. - Secure failure. A missing file becomes
404 Not Foundfor the user, while the log records the exception type. - Safe logging. The last request tries to inject a fake log line with
\n. Thedenymethod replaces line breaks with_, so the log shows one honest entry instead of a forgedadmin login OKline.