Java Reference ยท Language Features by Version
Secure coding in Java
Practical secure coding rules for Java: input validation, SQL injection, safe randomness, password hashing, deserialization, path traversal, secrets and more.
Most Java security problems are not exotic. They come from trusting input, building queries from strings, using weak randomness or hashes, leaking secrets and deserializing untrusted data. Java's memory safety removes whole classes of bugs (buffer overflows, use-after-free), but it does not stop injection, broken authorization or bad cryptography.
This page lists the practices that prevent the most common mistakes, with runnable demonstrations of the ones the sandbox can show. It is a checklist, not a full security course: threat modeling, dependency scanning and an independent review matter just as much.
// The central rule: data is never code // Bad : "SELECT * FROM users WHERE name = '" + name + "'" // Good: a prepared statement with a ? placeholder
Validate input, encode output
Treat every value that crosses a trust boundary (HTTP parameters, files, environment variables, messages, database content written by other systems) as untrusted. Validate it against what you expect: type, length, range, allowed characters. Prefer an allow list ("digits only") to a deny list ("not <script>"). Then encode data for the place it is going: HTML-escape for HTML, parameterize for SQL, quote for shell arguments (better, pass an argument array to ProcessBuilder, never a shell string).
Try it
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.
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.
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.
Practices that matter
- Parameterize every query. JDBC
PreparedStatement, JPA named parameters and Spring'sNamedParameterJdbcTemplateall keep data out of the SQL text. Table and column names cannot be parameters: map user choices to a fixed allow list. - Hash passwords with a slow, salted algorithm: Argon2id, bcrypt, scrypt or PBKDF2 with a high iteration count. Never MD5 or a bare SHA-256, and never store plain text or reversible encryption.
- Use
SecureRandomfor anything secret: tokens, session ids, salts, keys.java.util.RandomandMath.random()are predictable. - Do not invent cryptography. Use
AES/GCM/NoPadding(authenticated encryption) with a fresh random nonce for each message, via a vetted library when possible (for example Tink). Avoid ECB mode, DES, RC4, MD5 and SHA-1 for security. - Avoid native Java serialization of untrusted data; it has produced many remote-code-execution bugs. Prefer JSON or another data format, and if you must deserialize objects, set an
ObjectInputFilter(JVM-wide with-Djdk.serialFilter=...). Records andreadObjecthardening help, but a filter is the real defense. - Never trust file names and paths. Normalize and check
startsWiththe intended base directory, as shown above; do not build paths by string concatenation. Zip entry names can contain..("zip slip"). - Run external programs with an argument list:
new ProcessBuilder("convert", inputPath, outputPath). NeverRuntime.exec("convert " + userInput)through a shell. - Prefer HTTPS everywhere and keep certificate and hostname verification on. Do not install a trust-all
TrustManagerto "make the error go away". - Keep secrets out of source and logs: use environment variables, a secrets manager or a vault. Store passwords in
char[]where convenient and clear it, but rememberStringcopies may remain in memory; the larger risk is logging them. - Limit what errors reveal. Return a generic message to the user and log the details with a correlation id. Never print stack traces to HTTP responses.
- Check authorization on the server for every request, not just whether the user is logged in. Do not rely on hidden fields or client-side checks.
- Keep dependencies current. Run a dependency scanner (OWASP Dependency-Check, Dependabot, Snyk) and watch for advisories such as the Log4Shell vulnerability of 2021.
- Use the least privilege that works: database accounts with only the needed rights, containers that run as non-root, narrow file permissions.
- Know the removed Java features. The
SecurityManagerwas deprecated for removal in Java 17 and permanently disabled in Java 24; sandboxing is now done at the operating system or container level.
Usage notes
- Immutability helps security. Immutable objects cannot be changed after validation (check-then-use bugs). Make defensive copies of mutable arguments and return values when a class holds invariants.
- Integer overflow is silent. Use
Math.addExactandMath.multiplyExactwhen sizes and prices come from outside. equalson secrets can leak timing. UseMessageDigest.isEqualfor tokens and MACs.- Regular expressions can be attacked with catastrophic backtracking (ReDoS). Limit the input length and avoid nested quantifiers like
(a+)+. - Reflection and
--add-opensbypass encapsulation; limit them to places that need them. - The OWASP Top 10 and the SEI CERT Oracle Coding Standard for Java are good public checklists to review.
Related
- SecureRandom
- Serializable
- Logging
- Tutorial: Web security basics
- Tutorial: Serialization