Java Security

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 241 of 306

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.

LayerWhat it protectsMain pieces
LanguageMemory corruption, invalid castsType safety, bounds checks, no pointer arithmetic, garbage collection
JVMMalformed or tampered bytecodeBytecode verifier, class loaders
ModulesAccess to JDK internalsStrong encapsulation (module-info)
JCA / JCEData confidentiality and integrityjava.security, javax.crypto (hashing, encryption, signatures)
PKIIdentity and trustKeyStore, java.security.cert, certificate paths
JSSEData on the networkjavax.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 throws ArrayIndexOutOfBoundsException instead of returning whatever sits in memory after the array.
  • The cast from String to Integer is checked at runtime and fails with ClassCastException.
  • toUpperCase() returns a new string. The original role cannot 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 with InaccessibleObjectException, because the java.base module does not open java.lang to your code.
  • The string keeps its original value. Only a command-line flag such as --add-opens can 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.
  • SUN covers hashing and random numbers, SunJCE covers encryption and MACs, and SunJSSE covers 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 classPackageUsed for
MessageDigestjava.securityHashing (SHA-256, SHA3-256)
Macjavax.cryptoMessage authentication codes (HmacSHA256)
Cipherjavax.cryptoEncryption and decryption (AES, RSA)
KeyGeneratorjavax.cryptoSecret keys (AES)
KeyPairGeneratorjava.securityPublic/private key pairs (RSA, EC, Ed25519)
Signaturejava.securityDigital signatures
SecretKeyFactoryjavax.cryptoKeys from passwords (PBKDF2)
SecureRandomjava.securityCryptographically strong random numbers
KeyStorejava.securityStoring 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. A TreeSet sorts them.
  • MessageDigest.getInstance("SHA-256") returns an object from the SUN provider. digest() hashes the bytes, and HexFormat (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 MD5 and SHA-1 are 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 the java.security file.
  • jdk.tls.disabledAlgorithms lists protocols and algorithms that TLS connections refuse, such as SSLv3, TLSv1 and TLSv1.1.
  • jdk.certpath.disabledAlgorithms lists algorithms that are rejected in certificate chains, such as MD2 and MD5.

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() returns null, because no Security Manager is installed.
  • Since Java 18, System.setSecurityManager throws UnsupportedOperationException unless 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:

  1. Version check. Runtime.version().feature() returns the major version, such as 21. Old releases miss security fixes, so the check fails below Java 21.
  2. Hash algorithms. isAvailable tries MessageDigest.getInstance and turns NoSuchAlgorithmException into false.
  3. AES-256. Cipher.getMaxAllowedKeyLength("AES") returns Integer.MAX_VALUE when no export limits apply, which has been the default since Java 9.
  4. Strong randomness. SecureRandom.getInstanceStrong() returns the strongest generator configured in securerandom.strongAlgorithms, such as NativePRNGBlocking on Linux.
  5. 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 match TLSv1.3.
  6. Report. Each check prints [PASS] or [FAIL], and the totals at the end make the result easy to read in a deployment log.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Security and get answers drawn from it.

Signed-in readers only.