Java Secure Coding

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 242 of 306

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.

PrincipleMeaningExample in Java
Validate inputTreat all outside data as untrustedAllowlist regex for file names
Least privilegeGive code and users only the access they needRole checks, private fields
Fail securelyErrors must not open access or leak detailsGeneric error messages
Defense in depthUse more than one protective layerValidation and path checks
Minimize exposureKeep secrets out of logs and memoryMasked toString(), wiped char[]
Prefer immutabilityObjects that cannot change cannot be tampered withList.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:

  • UnsafeCourse stores the caller's ArrayList. When the caller adds "Intruder" to its own list, the course changes too, and students() hands out the same list for anyone to modify.
  • SafeCourse uses List.copyOf, which makes an immutable copy. Later changes to input do not reach it, and add throws UnsupportedOperationException.

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 as LocalDate.


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.
  • maskCard keeps only the last four digits, which is enough for a support team to identify a card.
  • Arrays.fill(password, '\0') overwrites every character. A String would 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.get return null, and unboxing it throws NullPointerException.
  • The catch block logs the real exception together with a short random reference id.
  • The caller only sees Request failed and 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:

  • resolve joins the base folder and the user's name. normalize() removes . and .. parts, so ../../../etc/passwd becomes /etc/passwd.
  • startsWith(UPLOAD_DIR) compares whole path elements, not just characters, so a folder named uploads-old would not pass by accident.
  • An absolute name such as /etc/shadow replaces 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,000 is 3 billion, which is larger than Integer.MAX_VALUE (2,147,483,647). The plain * wraps to a negative number without any warning.
  • Math.multiplyExact detects the overflow and throws ArithmeticException, so the bad value never reaches the rest of the program.
  • Casting one operand to long selects the long version of multiplyExact, 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'='1 closes 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 TABLE command.

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$Student and java.lang.* are allowed, maxdepth=5 limits nesting, and the final !* rejects every other class.
  • The Student record passes the filter and is read normally.
  • A HashMap is not on the list, so readObject throws InvalidClassException with the status REJECTED before 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:

  1. Least privilege. Only the roles in ALLOWED_ROLES may download. A guest gets 403 Forbidden.
  2. Allowlist validation. SAFE_NAME accepts only letters, digits, _ and -, followed by .pdf, .txt or .csv. Any /, .. or newline makes the name invalid, as explained further in Java Input Validation.
  3. Defense in depth. The normalize() and startsWith check would still stop path traversal if someone later relaxed the regex.
  4. Resource limits. big.csv is larger than MAX_BYTES, so the service refuses it instead of loading a huge file into memory.
  5. Secure failure. A missing file becomes 404 Not Found for the user, while the log records the exception type.
  6. Safe logging. The last request tries to inject a fake log line with \n. The deny method replaces line breaks with _, so the log shows one honest entry instead of a forged admin login OK line.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Secure Coding and get answers drawn from it.

Signed-in readers only.