Java Security
Java security is the set of language rules, JVM checks and standard APIs that protect Java programs and the data they handle. It covers memory safety, strong encapsulation of the JDK, cryptography, secure network connections and certificates.
You use these features every time you hash a password, call an HTTPS API or store a private key. This lesson gives you a map of the Java security architecture, shows how to inspect it from code, and prepares you for the lessons that follow, such as Java Secure Coding and Java Cryptography Basics.
The Java Security Architecture
Java security is built in layers. Each layer protects against a different kind of problem, and the higher layers depend on the lower ones.
| Layer | What it protects | Main pieces |
|---|---|---|
| Language | Memory corruption, invalid casts | Type safety, bounds checks, no pointer arithmetic, garbage collection |
| JVM | Malformed or tampered bytecode | Bytecode verifier, class loaders |
| Modules | Access to JDK internals | Strong encapsulation (module-info) |
| JCA / JCE | Data confidentiality and integrity | java.security, javax.crypto (hashing, encryption, signatures) |
| PKI | Identity and trust | KeyStore, java.security.cert, certificate paths |
| JSSE | Data on the network | javax.net.ssl (TLS), java.net.http.HttpClient |
Note: The JCA is the Java Cryptography Architecture, the JCE is the Java Cryptography Extension and JSSE is the Java Secure Socket Extension. Today they all ship with every JDK.
Language-Level Safety in Java
Many attacks on C and C++ programs work by reading or writing memory outside a buffer. Java blocks this whole class of bugs. Every array access is checked, every cast is checked, and you cannot turn a number into a memory address.
public class LanguageSafety {
public static void main(String[] args) {
int[] scores = {90, 75, 60};
// 1. Bounds checking: reading past the end is stopped, not allowed to read random memory
try {
System.out.println(scores[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Blocked: " + e.getMessage());
}
// 2. Type safety: an invalid cast fails at runtime instead of corrupting memory
Object value = "admin";
try {
Integer number = (Integer) value;
System.out.println(number);
} catch (ClassCastException e) {
System.out.println("Blocked: invalid cast to Integer");
}
// 3. Immutable strings: "changing" a String creates a new object
String role = "user";
String upper = role.toUpperCase();
System.out.println("role = " + role + ", upper = " + upper);
}
}
Output:
Blocked: Index 3 out of bounds for length 3
Blocked: invalid cast to Integer
role = user, upper = USER
How it works:
scores[3]is outside the array, so the JVM throwsArrayIndexOutOfBoundsExceptioninstead of returning whatever sits in memory after the array.- The cast from
StringtoIntegeris checked at runtime and fails withClassCastException. toUpperCase()returns a new string. The originalrolecannot be changed, which makes strings safe to share between classes and threads.
Strong Encapsulation of JDK Internals
Since Java 9, the JDK is split into modules. Since Java 17, code outside the JDK cannot open private members of JDK classes with reflection, even with setAccessible(true). This stops libraries and attackers from changing the internal state of classes such as String.
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
public class EncapsulationCheck {
public static void main(String[] args) throws Exception {
String password = "secret";
// Try to reach the private byte[] inside String and change it
Field valueField = String.class.getDeclaredField("value");
try {
valueField.setAccessible(true);
System.out.println("Internal field opened (this should not happen)");
} catch (InaccessibleObjectException e) {
System.out.println("Blocked by the module system:");
System.out.println(e.getMessage().substring(0, e.getMessage().indexOf(" accessible")));
}
System.out.println("password is still: " + password);
}
}
Output:
Blocked by the module system:
Unable to make field private final byte[] java.lang.String.value
password is still: secret
How it works:
getDeclaredField("value")can still describe the private field, as you saw in the Java Reflection API lesson.setAccessible(true)fails withInaccessibleObjectException, because thejava.basemodule does not openjava.langto your code.- The string keeps its original value. Only a command-line flag such as
--add-openscan break this rule, and that is a visible, deliberate choice.
Java Cryptography Architecture and Security Providers
The JCA separates what you ask for from who implements it. You ask for an algorithm by name, and a provider supplies the code. The JDK ships with several providers, and you can add more, such as Bouncy Castle or a hardware security module.
import java.security.Provider;
import java.security.Security;
public class ListProviders {
public static void main(String[] args) {
Provider[] providers = Security.getProviders();
System.out.println("Installed security providers (in priority order):");
for (int position = 0; position < providers.length; position++) {
Provider provider = providers[position];
System.out.printf("%2d. %-10s %s%n", position + 1, provider.getName(), provider.getVersionStr());
}
}
}
Output (versions depend on your JDK):
Installed security providers (in priority order):
1. SUN 21
2. SunRsaSign 21
3. SunEC 21
4. SunJSSE 21
5. SunJCE 21
6. SunJGSS 21
7. SunSASL 21
8. XMLDSig 21
9. SunPCSC 21
10. JdkLDAP 21
11. JdkSASL 21
12. SunPKCS11 21
How it works:
Security.getProviders()returns the installed providers in priority order.- When you call
getInstance("SHA-256"), the JCA asks each provider in this order and uses the first one that supports the algorithm. SUNcovers hashing and random numbers,SunJCEcovers encryption and MACs, andSunJSSEcovers TLS.
Engine Classes and getInstance()
Each type of security service has an engine class with a static getInstance(algorithm) factory method. You never create these objects with new.
| Engine class | Package | Used for |
|---|---|---|
MessageDigest | java.security | Hashing (SHA-256, SHA3-256) |
Mac | javax.crypto | Message authentication codes (HmacSHA256) |
Cipher | javax.crypto | Encryption and decryption (AES, RSA) |
KeyGenerator | javax.crypto | Secret keys (AES) |
KeyPairGenerator | java.security | Public/private key pairs (RSA, EC, Ed25519) |
Signature | java.security | Digital signatures |
SecretKeyFactory | javax.crypto | Keys from passwords (PBKDF2) |
SecureRandom | java.security | Cryptographically strong random numbers |
KeyStore | java.security | Storing keys and certificates |
The example lists the hash algorithms this JDK supports, then uses one of them.
import java.security.MessageDigest;
import java.security.Security;
import java.util.HexFormat;
import java.util.Set;
import java.util.TreeSet;
public class EngineClasses {
public static void main(String[] args) throws Exception {
// Which algorithms does this JDK offer for the MessageDigest engine?
Set<String> digests = new TreeSet<>(Security.getAlgorithms("MessageDigest"));
System.out.println("MessageDigest algorithms: " + digests);
// Ask for an implementation by name; the JCA picks a provider for us
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] hash = sha256.digest("GOCOURSE".getBytes());
System.out.println("Provider used: " + sha256.getProvider().getName());
System.out.println("SHA-256: " + HexFormat.of().formatHex(hash));
// Asking for an algorithm that does not exist fails clearly
try {
MessageDigest.getInstance("SHA-999");
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
MessageDigest algorithms: [MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256, SHA3-224, SHA3-256, SHA3-384, SHA3-512]
Provider used: SUN
SHA-256: 4f82dcf37663a4c0b4caa202e3c22defe84ad7bb2d4559d85b655395dd78996e
Error: SHA-999 MessageDigest not available
How it works:
Security.getAlgorithms("MessageDigest")collects the algorithm names from all providers. ATreeSetsorts them.MessageDigest.getInstance("SHA-256")returns an object from theSUNprovider.digest()hashes the bytes, andHexFormat(Java 17+) prints them as hex.- An unknown name throws the checked
NoSuchAlgorithmException, so a typo in an algorithm name never fails silently.
Note: Algorithm names such as
MD5andSHA-1are still available for compatibility with old files and protocols. Their presence does not mean they are safe to use for new security work.
Java Security Properties
The JDK reads security settings from the java.security file in $JAVA_HOME/conf/security. These properties control default keystore types, random sources and, most importantly, which old algorithms are disabled.
import java.security.Security;
public class SecurityProperties {
public static void main(String[] args) {
String[] propertyNames = {
"keystore.type",
"securerandom.source",
"jdk.tls.disabledAlgorithms",
"jdk.certpath.disabledAlgorithms"
};
for (String name : propertyNames) {
String value = Security.getProperty(name);
// Long values are trimmed so the output stays readable
String shortValue = value.length() > 60 ? value.substring(0, 60) + "..." : value;
System.out.println(name + " = " + shortValue.replaceAll("\\s+", " "));
}
}
}
Output:
keystore.type = pkcs12
securerandom.source = file:/dev/random
jdk.tls.disabledAlgorithms = SSLv3, TLSv1, TLSv1.1, DTLSv1.0, RC4, DES, MD5withRSA, DH ke...
jdk.certpath.disabledAlgorithms = MD2, MD5, SHA1 jdkCA & usage TLSServer, RSA keySize < 1024, ...
How it works:
Security.getProperty(name)reads a value from thejava.securityfile.jdk.tls.disabledAlgorithmslists protocols and algorithms that TLS connections refuse, such asSSLv3,TLSv1andTLSv1.1.jdk.certpath.disabledAlgorithmslists algorithms that are rejected in certificate chains, such asMD2andMD5.
Note: JDK updates tighten these lists over time. Keeping your JDK patched is one of the easiest Java security wins, because weak algorithms get disabled for you.
The Security Manager Is Gone
Older Java versions had a Security Manager that sandboxed untrusted code, mainly for applets. It was deprecated for removal in Java 17 (JEP 411) and permanently disabled in Java 24 (JEP 486). Modern applications use operating system and container isolation instead.
public class SecurityManagerStatus {
@SuppressWarnings("removal")
public static void main(String[] args) {
System.out.println("Java version: " + Runtime.version().feature());
System.out.println("Security Manager installed: " + (System.getSecurityManager() != null));
try {
System.setSecurityManager(new SecurityManager());
System.out.println("Security Manager enabled");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot enable: " + e.getMessage());
}
}
}
Output (on Java 21):
Java version: 21
Security Manager installed: false
Cannot enable: The Security Manager is deprecated and will be removed in a future release
How it works:
System.getSecurityManager()returnsnull, because no Security Manager is installed.- Since Java 18,
System.setSecurityManagerthrowsUnsupportedOperationExceptionunless the JVM is started with-Djava.security.manager=allow. From Java 24, even that flag cannot turn it back on. @SuppressWarnings("removal")hides the compiler warning about using a deprecated-for-removal API.
Real-World Example: A JDK Security Health Check
Before you deploy, it helps to confirm that the JDK on a server has the security features your application needs. This program checks the Java version, strong hashing, AES-256 support, a strong random number generator, TLS 1.3 and the disabled-algorithm lists.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import java.util.List;
import javax.crypto.Cipher;
import javax.net.ssl.SSLContext;
public class SecurityHealthCheck {
private static int passed = 0;
private static int failed = 0;
public static void main(String[] args) throws Exception {
System.out.println("=== JDK Security Health Check ===");
// 1. A supported, modern Java release
int feature = Runtime.version().feature();
check("Java version is 21 or newer (found " + feature + ")", feature >= 21);
// 2. Strong hash algorithms are available
check("SHA-256 and SHA3-256 available", isAvailable("SHA-256") && isAvailable("SHA3-256"));
// 3. Unlimited-strength crypto: AES-256 keys are allowed
int maxAesKey = Cipher.getMaxAllowedKeyLength("AES");
check("AES-256 allowed (max key length " + (maxAesKey == Integer.MAX_VALUE ? "unlimited" : maxAesKey) + ")",
maxAesKey >= 256);
// 4. A strong SecureRandom can be created
SecureRandom strongRandom = SecureRandom.getInstanceStrong();
check("Strong SecureRandom: " + strongRandom.getAlgorithm(), strongRandom != null);
// 5. TLS 1.3 is supported and old protocols are disabled
List<String> protocols = Arrays.asList(
SSLContext.getDefault().getSupportedSSLParameters().getProtocols());
check("TLSv1.3 supported", protocols.contains("TLSv1.3"));
String disabledTls = Security.getProperty("jdk.tls.disabledAlgorithms");
check("SSLv3, TLSv1 and TLSv1.1 disabled",
disabledTls.contains("SSLv3") && disabledTls.contains("TLSv1,") && disabledTls.contains("TLSv1.1"));
// 6. MD5 is no longer trusted for certificate signatures
String disabledCert = Security.getProperty("jdk.certpath.disabledAlgorithms");
check("MD5 rejected for certificates", disabledCert.contains("MD5"));
System.out.printf("Result: %d passed, %d failed%n", passed, failed);
}
private static boolean isAvailable(String algorithm) {
try {
MessageDigest.getInstance(algorithm);
return true;
} catch (NoSuchAlgorithmException e) {
return false;
}
}
private static void check(String description, boolean ok) {
System.out.println((ok ? "[PASS] " : "[FAIL] ") + description);
if (ok) passed++; else failed++;
}
}
Output (on a current JDK 21 build):
=== JDK Security Health Check ===
[PASS] Java version is 21 or newer (found 21)
[PASS] SHA-256 and SHA3-256 available
[PASS] AES-256 allowed (max key length unlimited)
[PASS] Strong SecureRandom: NativePRNGBlocking
[PASS] TLSv1.3 supported
[PASS] SSLv3, TLSv1 and TLSv1.1 disabled
[PASS] MD5 rejected for certificates
Result: 7 passed, 0 failed
How it works:
- Version check.
Runtime.version().feature()returns the major version, such as21. Old releases miss security fixes, so the check fails below Java 21. - Hash algorithms.
isAvailabletriesMessageDigest.getInstanceand turnsNoSuchAlgorithmExceptionintofalse. - AES-256.
Cipher.getMaxAllowedKeyLength("AES")returnsInteger.MAX_VALUEwhen no export limits apply, which has been the default since Java 9. - Strong randomness.
SecureRandom.getInstanceStrong()returns the strongest generator configured insecurerandom.strongAlgorithms, such asNativePRNGBlockingon Linux. - TLS. The supported protocols come from the default
SSLContext, and the disabled list comes from the security property you saw earlier. The check looks for"TLSv1,"with a comma so that it does not matchTLSv1.3. - Report. Each check prints
[PASS]or[FAIL], and the totals at the end make the result easy to read in a deployment log.