Skip to content
Tutorials Center
My learning

Topics

Lesson 167 of 201 ยท JVM and Advanced Topics

Secure Coding in Java

Write safer Java. Validate input with allow-lists, stop path traversal and SQL injection, use SecureRandom, hash passwords with PBKDF2, filter deserialization.

Java removes whole families of bugs. There are no buffer overflows in normal code, array accesses are checked and memory is managed for you. But memory safety is not the same as security. Most real-world Java vulnerabilities are logic mistakes: trusting input that came from outside, building SQL out of strings, using a predictable random number for a login token, or turning attacker-controlled bytes back into objects.

This lesson covers the habits that prevent the most common problems. The mindset is simple. Everything that crosses a trust boundary is hostile until validated: HTTP parameters, file names, JSON bodies, environment variables, and even data from your own database if somebody else could have written it. Everything below follows from that idea. If you haven't yet, read Exception Best Practices and UUIDs, Hashing and Base64 first, because this lesson builds on both.

flowchart LR
    A["Untrusted input<br/>(request, file, message)"] --> B["Validate<br/>(allow-list)"]
    B --> C["Use safely<br/>(parameters, normalized paths)"]
    C --> D["Output<br/>(encode for the target)"]
    B -. "invalid" .-> E["Reject with a<br/>generic error"]

Validate on the way in, use data through safe APIs, and encode on the way out.

Validate input with allow-lists

There are two ways to check input. A deny-list tries to list bad things ("no <script>, no ', no --") and always loses, because attackers are more creative than lists. An allow-list describes exactly what is acceptable and rejects the rest. Prefer the allow-list every time.

A good validator checks type, length, range and format, in that order of cheapness. Regular expressions work well for formats. Use matches(), which must match the whole string, not find(), which would accept "ok<script>" because it contains an ok somewhere (see Regular Expressions):

Java Allow-list validation and path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last check is the one people forget. A file name from a user can contain .. segments. resolve happily builds /srv/uploads/../../etc/passwd, and only normalize() collapses it to /etc/passwd, which a startsWith(base) test then catches. This attack is called path traversal. In a real server, also resolve symbolic links with toRealPath() before the check, and generate your own file names (a UUID plus a fixed extension) rather than trusting the uploaded one.

Two more validation habits: validate on the server (client-side checks are only for convenience), and fail with a generic message. "Invalid username or password" tells an attacker nothing; "no such user" tells them which names exist.

Never build SQL with string concatenation

SQL injection is decades old and still on every top-ten list. The cause is always the same: user text is pasted into a query, so the database cannot tell where your SQL ends and their data begins. The cure is a PreparedStatement, which sends the query shape and the values separately, so a value is only ever data.

This example uses the in-memory H2 database that our Java runner provides. It runs the same lookup twice, first with concatenation and then with a parameter, using a hostile input:

Java SQL injection and PreparedStatement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The concatenated query turned into WHERE name = 'nobody' OR '1'='1', which is true for every row. Parameters can only replace values. You cannot bind a table or column name with ?; if you need a dynamic column, map the user's choice to a fixed set of allowed names (an enum or a Map) and put the matching constant into the SQL yourself. The same rule applies to JPA and Hibernate: named parameters are safe, string-built JPQL is not.

Randomness: Random versus SecureRandom

java.util.Random is a simple formula: given the same seed it produces the same numbers, and observing a few outputs lets an attacker compute the rest. It is fine for games and simulations, and never acceptable for anything an attacker must not guess: session IDs, password-reset tokens, API keys, nonces, salts.

java.security.SecureRandom draws from the operating system's cryptographic source. It is slower, but unpredictable. The usual job is generating a token and encoding it for transport:

Java Tokens with SecureRandom

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what the example does not print: the token itself. It differs on every run. A 256-bit token is long enough that guessing is hopeless; 128 bits (16 bytes) is the usual minimum. Don't hand-roll a token from Math.random(), System.currentTimeMillis() or UUID.randomUUID() for a secret you must protect from guessing, and don't call setSeed on a SecureRandom with a fixed value.

Passwords: slow, salted hashes

A plain SHA-256 of a password is not safe storage. SHA-256 is designed to be fast, so an attacker who steals the table can test billions of guesses per second, and identical passwords produce identical hashes. A password hash needs two properties:

  • A unique random salt per password, so equal passwords look different and precomputed tables are useless.
  • A deliberately slow algorithm with a work factor, so every guess is expensive.

The JDK ships PBKDF2 (PBKDF2WithHmacSHA256). Modern systems also use bcrypt, scrypt or Argon2 from a library such as Spring Security's PasswordEncoder; use one of those in a real application if you can. The JDK version shows the principle with no extra dependencies:

Java Salted password hashing with PBKDF2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three details matter. The stored string contains the iteration count and salt, so you can raise the work factor later and still verify old hashes. The comparison uses MessageDigest.isEqual, which takes the same time wherever the arrays differ, instead of Arrays.equals or String.equals, which stop at the first difference and leak information through timing. And the password is a char[], which you can overwrite with Arrays.fill(password, '\0') after use, whereas an immutable String stays in memory until garbage collected. Never log passwords, tokens or full request bodies, and keep secrets out of source code (read them from environment variables or a secrets manager).

Deserialization: the dangerous default

Java's built-in serialization turns an object graph into bytes and back. The problem is on the way back: ObjectInputStream.readObject() creates objects of whatever classes the stream names, and runs their deserialization code, before your program has a chance to look at the result. If an attacker controls the bytes and your classpath contains a class whose deserialization does something dangerous (a "gadget"), they can run code on your server. Attacks like this have hit some of the largest Java products.

The safest rule: do not deserialize untrusted data with Java serialization. Use a data format like JSON with a mapping library, and a fixed target type. If you must read serialized objects, install a deserialization filter that accepts only the classes you expect. The filter is consulted as the stream is read, before an object is created:

Java Filtering deserialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A process-wide filter can also be set with the jdk.serialFilter system property or ObjectInputFilter.Config.setSerialFilter, so even code you didn't write is covered. Records and plain data classes are safer targets than classes with custom readObject methods, but the filter is still your friend. For the same reason, treat XMLDecoder, XStream with default settings and other "object from text" libraries as equally dangerous when fed untrusted input.

More habits that pay off

  • Least privilege. Run the app as a non-admin user, give the database account only the rights it needs and expose only the ports you must.
  • Keep dependencies updated. Most breaches come from known-vulnerable libraries (Log4Shell is the famous example). Scan your build with a dependency checker and update regularly.
  • Don't leak details in errors. Show the user a short message and an error ID; log the stack trace on the server (see Logging).
  • Encode output for its destination. HTML needs HTML escaping, URLs need percent-encoding, SQL needs parameters. A template engine that escapes by default is better than doing it by hand.
  • Immutability helps. Immutable classes and defensive copies of arrays and dates stop callers from changing data after you validated it.
  • Use TLS everywhere and never disable certificate checks "just for testing"; that setting has a way of reaching production.
  • Don't invent cryptography. Use well-reviewed algorithms (AES-GCM for encryption, SHA-256 or better for hashing, Ed25519 or ECDSA for signatures) and libraries, with keys from a secure store.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which validation approach is the most reliable?

    An allow-list defines what is acceptable. Deny-lists always miss something, and client-side checks can be bypassed completely.
  2. 2. Why does resolveInside call normalize() before checking startsWith(base)?

    Without normalization, /srv/uploads/../../etc/passwd still starts with /srv/uploads. After normalize() it becomes /etc/passwd, and the check fails as it should.
  3. 3. Why does a PreparedStatement stop SQL injection?

    The database receives the statement structure first and the values afterwards. A value like x' OR '1'='1 is compared as a plain string.
  4. 4. Which should generate a password-reset token?

    SecureRandom is designed to be unpredictable. Random and Math.random() are deterministic formulas, and ids or counters are guessable.
  5. 5. What is the safest policy for Java serialization?

    Dangerous code can run while an object is being created, before your type check. Filters reject unexpected classes while the stream is being read.

Summary

  • Treat all input from outside as hostile: validate with allow-lists (type, length, range, format) on the server.
  • Normalize paths before checking they stay inside a base directory, and generate your own file names.
  • Always use PreparedStatement parameters; never concatenate user text into SQL. Only values can be parameters.
  • Use SecureRandom for anything that must be unpredictable; Random is for simulations.
  • Store passwords as slow, salted hashes (PBKDF2, bcrypt, scrypt or Argon2), compare with a constant-time method and keep secrets out of code and logs.
  • Avoid Java deserialization of untrusted bytes; otherwise filter classes with ObjectInputFilter.
  • Update dependencies, run with least privilege, and show users generic errors.

Next: Native Code: JNI and the Foreign Function API, where Java calls into C libraries.