Lesson · Security Essentials
Security essentials: the boundary you draw
13 min readSecurity Essentials
The SecurityManager is gone, and nothing replaced it inside the JVM: the trust boundary now lives at the process, the module and the container, plus every check your own code performs. This lesson covers the checks that matter most: input handling, password storage, symmetric crypto, secrets and the supply chain.
The security model after the SecurityManager
For most of Java's life a program could install a SecurityManager and sandbox itself from the inside: file opens, sockets and process launches consulted a policy. That model was retired deliberately, and it is worth knowing the dates because they show up in code reviews and interviews.
In JDK 24 the runtime cannot be put into that mode at all: enabling it on the command line is a startup error, and System.setSecurityManager throws UnsupportedOperationException. The API still exists in degraded form and a future release will remove it.
| Era | What is true of the SecurityManager |
|---|---|
| JDK 17 to 23 (JEP 411) | deprecated for removal; enabling it prints warnings; since JDK 18 the default value of java.security.manager is disallow |
| JDK 24 onward (JEP 486) | permanently disabled: cannot be enabled at startup, cannot be installed at run time, API degraded to no-ops |
- The boundary moved outward: the process, the module path and the container are where trust is decided now. Run untrusted work in its own process or its own container, not in a sandbox inside your JVM.
- Java's own hardening is strong encapsulation: the module system keeps JDK internals out of reach, which is why deep reflection into those packages fails. That wall, and its
--add-openskey, belongs to the reflection and encapsulation lesson. - Inside the boundary, your code is the gatekeeper: nothing will intercept a malicious string on your behalf, so the checks you write are the security model.
- Untrusted input is the default, not an exception case: a request body, a header, a file, a message from a queue, a database column that a different service once wrote.
There is no gatekeeper watching your method calls anymore. The boundary you draw is the security model, and it is drawn in ordinary code.
Untrusted input is the default
Most exploitable bugs share one shape: data crosses a trust boundary and is then used as if it were code, a query, a path or a record. The defence has two halves, and using one without the other fails.
| Injection class | How it works | The fix | Owner lesson |
|---|---|---|---|
| SQL injection | user text is concatenated into a statement and parsed as SQL | parameterised statements, never string building | sql-injection |
| Deserialization gadgets | bytes become objects whose read hooks execute attacker-chosen code | allow-list filters, and do not deserialize untrusted streams | serialization-security |
| Path traversal | user text becomes a file path that escapes the intended directory | resolve under a fixed base, then verify containment | this lesson |
| Log injection | newlines in user text forge or split log records | strip or escape control characters before logging | this lesson |
- Validate at the boundary: as soon as a value arrives, parse it into a typed, constrained form (an enum, an id with a known alphabet, a number in range) and reject everything else. Validation is about the value's shape, not its destination.
- Encode at the sink: the consumer of a value knows its grammar, so the escaping happens there: a bound SQL parameter, an HTML escape, a path join that stays inside a fixed base directory. Encoding is about the receiver's syntax.
- Allow-lists beat block-lists: a rule that names what is acceptable survives encodings and Unicode tricks; a rule that bans patterns eventually meets the pattern it forgot.
- Never let data select code: no dynamic class loading, no expression evaluation and no
execwhere a data structure would do.
Validation narrows the value; encoding protects the sink. A program that does only one of the two is still injectable, just less often.
Structure · entries, boundary, defences
nothing arrives trusted; the boundary is drawn in code
Passwords: make a stored leak expensive
Assume the user table will eventually be read by someone who should not have it. The only thing standing between them and every password is the cost of guessing, so the storage format is a decision about that moment.
- Read the stored record: algorithm, iteration count, salt, hash.
- Decode the salt and derive a candidate hash with the stored parameters, not the current defaults.
- Compare the candidate to the stored hash with MessageDigest.isEqual and return the boolean directly.
- On success, if the stored parameters are behind the current policy, rehash now while the plaintext is in hand.
- On failure, take the same amount of time as a success path where practical, and never include the password in a log line or an error message.
- Never store the password itself: not plain, not encrypted, not under a fast hash. MD5, SHA-1 and a single SHA-256 round are all designed to be quick, which is exactly the wrong property here.
- Hash with a deliberate work factor: PBKDF2 (in the JDK as PBKDF2WithHmacSHA256) with an iteration count in the hundreds of thousands, or bcrypt/Argon2 from a maintained library. Tune it so one verification takes tens of milliseconds on your hardware, and store the parameters next to the hash so you can raise them later.
- Salt per user, from SecureRandom: a random salt per record makes precomputed tables useless and stops identical passwords from colliding. Generating it is the randomness lesson's territory; here it is one call.
- Compare in constant time:
MessageDigest.isEqualexamines every byte of the first array, and the JDK documents that the time depends only on its length, not on the contents. Comparing hex strings withequalsexits at the first mismatch and leaks, in principle, how much of a guess was right. - Encryption is not the alternative: reversible storage means whoever holds the key holds the passwords. Slowness plus a salt is the whole mechanism, which is why the digest choice is the least interesting part of it.
A password hash is defined by its cost, not its digest. If verification is fast, the storage is weak no matter which algorithm name is printed next to it.
Symmetric crypto with javax.crypto
When the task is really confidentiality, the JDK ships the primitives through the Java Cryptography Architecture: javax.crypto for ciphers, java.security for keys, randomness and digests. The APIs are old but sound; the failure modes are in how they are used.
- Generate the key once and store it where the runtime can read it but a reader of the repository cannot.
- Generate a 12-byte nonce with SecureRandom for this message, and never reuse one under the same key.
- Initialise the cipher for encryption with a GCMParameterSpec of 128 bits and that nonce.
- Encrypt, then store or transmit the nonce together with the ciphertext, and authenticate the context that matters (iv, lengths, sender) as associated data.
- On decrypt, rebuild the same parameters and let AEADBadTagException surface instead of catching it and continuing.
- Choose authenticated encryption:
Cipher.getInstance("AES/GCM/NoPadding")with a 128-bit tag detects tampering on decrypt, which plain CBC does not. For new code, AEAD is the default; if you must compose, encrypt then MAC, never the reverse. - A nonce must never repeat under one key: GCM loses its security, not just its freshness, when a key and nonce pair is reused, potentially exposing the authentication subkey and making forgeries possible. Generate a fresh random nonce per message, store it with the ciphertext, and let
SecureRandomproduce it. - Never ECB: identical plaintext blocks become identical ciphertext blocks, leaking the structure of the data no matter how strong the key is.
- Keys come from a generator or a KDF:
KeyGenerator.getInstance("AES")for a fresh key, or a key derivation function for one derived from a secret. An AES-256 key is 32 random bytes, and it is not a passphrase typed into a constant. - In transit is a separate layer: TLS protects the channel, and the networking chapter owns it (
network-security). Application-level encryption protects the data, including at rest and inside systems TLS does not cover.
Modes fail in pairs. A block cipher with the wrong mode, or GCM with a reused nonce, is weaker than the algorithm name suggests; the choice of mode and nonce discipline is the security, not the key length.
Secrets and the supply chain
Two further leaks are structural rather than algorithmic: where the running system gets its credentials, and what code you choose to ship.
- Secrets do not live in the repository, the jar, or the image layer. Git history and registry layers are effectively permanent, so treat any committed credential as public and rotate it the moment it is found.
- Inject them at deploy time: environment variables populated by a secret manager, a mounted file with tight permissions, or a platform identity. The code reads a value; it does not know where the store lives, which keeps the two deployable apart.
- Rotate and scope them: one credential per service, least privilege for the runtime identity, and a rotation path that does not require a rebuild or a coordinated code change.
- Pin and scan what you depend on: fixed versions from a lock file, checksums or signatures on artifacts, a scanner wired into the build, and an SBOM so you can answer what you ship and where a new CVE lands.
- Fewer dependencies is a security decision: each one is code you agreed to run, and your direct list is usually a fraction of the resolved tree.
- Logging hygiene closes the loop: no tokens, passwords, session ids or personal data in logs, because logs are copied, shipped and retained far more widely than people assume.
A secret is only as safe as its least controlled copy. Rotation is what makes a leak survivable, so design for rotation before the first deploy.
The code review checklist
Run this list over any change that touches data, credentials or external input. It is short enough to use for real reviews, and it maps onto the sections above.
- Input: where does this value enter, and what constrains it before use? Every value from outside gets a typed, bounded form first.
- Authorization: who is allowed to do this, checked on the server against the current identity rather than hidden in the client.
- Secrets: is anything sensitive in source, committed config, logs or error messages?
- Crypto: is this an AEAD or a vetted library, with a fresh nonce and a key from a generator rather than a constant?
- Dependencies: what did this change add to the tree, and is it pinned and scanned?
- Logging: would you be comfortable if these lines were published, with attribution to the user they describe?
Six questions, every change. They are cheap to ask and they catch the failure classes that the JVM will no longer catch for you.
Choices lab · pick an approach per task
one chip per taskPick an approach above and the verdict appears here, with the reason and the trap it hides.
The SHA-256 password hash
Salting SHA-256 is a genuine improvement over storing the raw digest, and it still fails: general-purpose hardware computes billions of SHA-256 hashes per second, so a stolen table falls at a rate the attacker chooses. The missing ingredient is not a different digest but deliberate slowness plus a per-user salt: PBKDF2 tuned to tens of milliseconds, or bcrypt/Argon2 from a maintained library, with the parameters stored next to each hash so they can be raised as hardware improves. Swapping SHA-256 for SHA-512 changes nothing about the attack; the cost curve is the security.
Interview angles
How do you store a user password?+
As a hash from a deliberately slow function with a per-user random salt: PBKDF2 with a high iteration count, or bcrypt or Argon2 from a maintained library. Verification re-derives with the stored parameters and compares with MessageDigest.isEqual. Reversible encryption is not an option, because whoever holds the key holds the passwords.
What replaced the SecurityManager?+
Nothing inside the JVM, and that is the design: the trust boundary moved to the process, module and container. JDK 17 deprecated it for removal (JEP 411) and JDK 24 permanently disabled it (JEP 486), so sandboxing is now an operating system or container concern, and the JDK contributes strong encapsulation instead.
Common misconception: That a replacement API exists and simply needs adopting. There is no in-JVM sandbox switch any more; the design decision was not to build one.
What goes wrong when a GCM nonce repeats under one key?+
The security of the mode, not just its freshness: reuse can expose the authentication subkey and makes forged messages possible, so a fresh random 12-byte nonce per message, generated with SecureRandom and stored with the ciphertext, is the rule. Never derive the nonce from something predictable such as a counter that can reset.
Why do you need both validation and encoding?+
They defend different places. Validation turns an untrusted value into something typed and bounded at the boundary; encoding protects the sink, because only the SQL parser, the HTML renderer or the file system knows its own grammar. A bound SQL parameter with no validation is still safe from injection, but validation is what keeps the rest of the logic honest about what the value can be.