Safeguard
DevSecOps

The Java Cheat Sheet Developers Actually Need for Secure Code

Most Java cheat sheets stop at syntax. This one is the security-focused reference: the APIs, patterns, and one-liners that keep injection, deserialization, and crypto bugs out of your code.

Marcus Chen
DevSecOps Engineer
5 min read

This Java cheat sheet skips the syntax refresher and gives you the security-relevant patterns that actually prevent bugs — safe database access, deserialization defense, correct crypto, and dependency hygiene. A cheat sheet java developers reach for should not just remind you how a for loop works; it should keep you from writing the SQL injection, the unsafe readObject, and the ECB-mode cipher that turn into incidents. What follows is the reference we hand new engineers: the idioms to reach for by reflex and the ones to treat as red flags in review.

Safe database access

The single most common serious bug in Java web code is string-concatenated SQL. The fix is always parameterized queries, never manual escaping.

// Vulnerable: user input concatenated into SQL
String sql = "SELECT * FROM users WHERE name = '" + name + "'";

// Safe: PreparedStatement binds the value, never interprets it as SQL
String sql = "SELECT * FROM users WHERE name = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, name);
    ResultSet rs = ps.executeQuery();
}

If you use JPA or Hibernate, the same rule applies: use named parameters (:name) or positional binding, never string-built JPQL. Dynamic ORDER BY or table names cannot be parameterized, so validate those against a fixed allowlist rather than passing them through.

Deserialization: the pattern that caused Java's worst bugs

Native Java deserialization of untrusted data is the mechanism behind a long line of remote-code-execution vulnerabilities. The rule on the cheat sheet is blunt: never call ObjectInputStream.readObject() on data you do not fully control.

// Red flag in review
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
Object o = ois.readObject();

For data interchange, use JSON with a well-configured library instead. If you use Jackson, keep default typing disabled — enabling it is what turned jackson-databind into a repeated CVE magnet, as covered in our Jackson databind security guide. If you genuinely must deserialize Java objects, apply a serialization filter (ObjectInputFilter, available since Java 9) that allowlists the exact classes permitted:

ObjectInputFilter filter =
    ObjectInputFilter.Config.createFilter("com.example.Dto;!*");
ois.setObjectInputFilter(filter);

Cryptography one-liners done right

Crypto bugs are usually about defaults. Two rules cover most of them: never use ECB mode, and never roll your own key or IV handling.

// Wrong: ECB leaks structure; predictable and insecure
Cipher c = Cipher.getInstance("AES");           // defaults to ECB
Cipher c2 = Cipher.getInstance("AES/ECB/PKCS5Padding");

// Right: authenticated encryption with a random 12-byte IV
byte[] iv = new byte[12];
SecureRandom.getInstanceStrong().nextBytes(iv);
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));

For password storage, do not use MessageDigest with SHA-256 — use a purpose-built password hash. For randomness that matters, use SecureRandom, never java.util.Random or Math.random().

XML and XXE

XML parsers in Java process external entities by default, which is an XXE (XML External Entity) vulnerability waiting to read your local files or reach internal services. Disable the dangerous features explicitly:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);

Keep this snippet on the cheat sheet, because the secure configuration is verbose and easy to forget on the third parser you set up.

Input handling and output encoding

Trust nothing from the request. Validate on the way in against expected type and range, and encode on the way out based on the context you are writing into — HTML body, HTML attribute, JavaScript, or URL each need different encoding. For web output, use a template engine that auto-escapes (Thymeleaf does by default) rather than building HTML with string concatenation. Path traversal is prevented by canonicalizing and confirming the resolved path stays inside the intended directory:

Path base = Paths.get("/srv/uploads").toRealPath();
Path target = base.resolve(userFilename).normalize();
if (!target.startsWith(base)) {
    throw new SecurityException("Path traversal attempt");
}

Dependency hygiene: the layer syntax cheat sheets ignore

The code you write is a small fraction of what ships. Log4Shell (CVE-2021-44228) was not a bug in anyone's application code — it was a single logging dependency that turned a log line into remote code execution across the entire industry. The cheat-sheet rule: know your dependency tree and keep it current.

# Maven: list the full dependency tree
mvn dependency:tree

# Check dependencies against known vulnerabilities
mvn org.owasp:dependency-check-maven:check

OWASP Dependency-Check is the free baseline; a dedicated SCA tool adds transitive-reachability analysis so you patch the CVE your code path actually triggers instead of every one in the tree. Either way, the point is that a Java cheat sheet that stops at language syntax leaves out the layer where most real breaches now happen.

A quick review checklist

When you review Java code, scan for these first: string-built SQL, readObject on request data, Cipher.getInstance("AES") with no mode, XML parsing without XXE hardening, Random used for anything security-sensitive, and dependency versions that have not moved in a year. Those six patterns account for a large share of the serious findings in typical Java codebases, and catching them in review is far cheaper than catching them in a pentest.

FAQ

What should a security-focused Java cheat sheet include?

Parameterized SQL, safe deserialization (avoid readObject on untrusted data), authenticated crypto (AES-GCM, never ECB), XXE-hardened XML parsing, correct use of SecureRandom, and dependency scanning. Syntax reminders are secondary.

Is Java deserialization always dangerous?

Native deserialization is dangerous only on untrusted input, but that is exactly where developers get caught. Prefer JSON with a hardened parser, and if you must deserialize Java objects, apply an ObjectInputFilter allowlist.

How do I check my Java dependencies for vulnerabilities?

Run mvn org.owasp:dependency-check-maven:check for a free baseline, or use an SCA tool that adds transitive and reachability analysis. Log4Shell showed that dependency risk, not your own code, is often the bigger exposure.

Why avoid Cipher.getInstance("AES") in Java?

Because it silently defaults to ECB mode, which leaks patterns in the plaintext and provides no integrity. Use AES/GCM/NoPadding with a random IV for authenticated encryption instead.

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.