Posts

A Guide to Java Application Security

Jan 28, 2026
Dmitry Chuyko
13.6

The growing dependence on digital services is a fertile ground for cybercrime that affects millions of people worldwide and costs billions in losses every year.

Most Java security incidents are caused by predictable engineering debt: vulnerable dependencies, weak boundaries, and zero visibility when something goes wrong.

This article breaks down the specific best practices for securing modern Java applications. By the end, you’ll get a checklist that covers code, runtime, and containers. 

Java Security Best Practices

Avoid Using JDK Internal Components

Modules were introduced in Java 9 to enhance Java integrity and protect internal JDK components from ubiquitous access. The process peaked with JEP 403: Strongly Encapsulate JDK Internals in JDK 17.

However, versions 9 to 16 allowed developers to use reflection to access internal elements.

If you are not planning to migrate to version 17 or newer in the near future, we strongly recommend avoiding reflection and migrating to standard APIs. Internal APIs may transfer sensitive data or define privileged operations, so external access compromises the platform’s security.

Minimize Serialization Risks

Java serialization enables the developers to convert an object into a byte stream for further transmission or storage. In turn, deserialization is used for converting byte streams back into original objects. The security issues are related to the deserialization part because methods of a deserialized object may be indirectly invoked before any checks are performed on reconstructed objects. As a result, a stream of unknown data becomes a Java object with potentially malicious data, leading to the risk of remote code execution.

A series of exploited vulnerabilities related to deserialization proves that the serialization mechanism is inherently unsafe. MITRE’s CWE Top 25 (2025) still lists CWE-502: Deserialization of Untrusted Data among the most dangerous weaknesses.

There is a goal to remove serialization in its current form from Java as part of Project Amber. But for now, it is better to avoid using serialization and deserialization as much as possible. If this is not an option, minimize the risks by applying serialization filters.

Serialization filters scan and validate the incoming data streams. You can create

  • Pattern-based filters consist of specific patterns defined in properties, in a config file, or on the command line. They accept or reject classes in simple scenarios; 
  • Custom filters are specified in the application’s code and implemented as patterns, methods, lambda expressions, or classes. They are applied to an individual stream or all streams in a process. 

Pattern-based and custom filters allow the developers to create blacklists to reject classes not allowed for deserialization or whitelists to accept only recognized and accepted classes.

Serialization filters are available starting with JDK 9. In Java 17, the mechanism was enhanced with context-specific filters that can be tailored to various contexts and use cases.

Apply Input Sanitation Techniques

You should always be suspicious about any external input because it may contain malicious data allowing an injection attack, most common being SQL injections (when an attacker includes SQL queries into the user input data) and cross-site scripting (XSS, an injection of malicious code into websites). In addition, we now have language model prompt injections.

To prevent SQL injections,

  • Parametrize SQL queries with prepared statements that act as templates, where user input is loaded dynamically. As the parameters are already given in these prepared statements, malicious queries won’t take effect;
  • Prefer whitelists to blacklists when validating user input.

As for the XSS attacks, be sure to

  • Use modern web frameworks with better XSS prevention practices in place;
  • Implement output encoding for transforming data into a safe format. OWASP provides an output encoder specifically for Java applications;
  • Avoid placing variables into dangerous contexts (directly in the script, in callback functions, etc.) even with output encoding in place;
  • Apply HTML sanitization to convert HTML input into a safe string. OWASP recommends using DOMPurify for that purpose.

Take Advantage of Java API for XML Processing (JAXP)

Java offers an API for XML Processing (JAXP) that enables developers to protect their applications from XPath and other XML-related attacks. The fundamental mechanism of the API is Feature for Secure Processing (FSP), which instructs XML processors to try and process XML securely. JAXP allows developers to

  • Set the XML processing limits to prevent malformed XML sources from excessive memory consumption;
  • Restrict external access by defining allowed and forbidden external connections. This function can be used with resolvers and catalogs to reduce the risk of malicious external connections further. 

Use Strong Encryption and Password Hashing

Cryptographic Failures take the fourth place in the 2025 OWASP Top 10 security risks, meaning that many developers don’t implement proper encryption mechanisms. In the worst-case scenario, user passwords or other sensitive data are stored as plain text. Sometimes, obsolete or unreliable hashing mechanisms are used, and sometimes, sensitive data is automatically decrypted upon retrieval from the database.

Therefore, you should

  • Avoid using deprecated or legacy protocols (e.g., FTP, SMTP) and cryptographic algorithms (MD5, SHA1, etc.);
  • Prefer hashing to encryption for passwords because hashing is a one-way function that converts a password into a string that cannot be reversed. Use strong adaptive and salted hashing functions as well as recommended hashing algorithms such as Argon2id for password storage;
  • Prefer authenticated encryption to simple encryption;
  • Always use known and trusted encryption libraries. For instance, Spring Security offers numerous authentication and authorization features out-of-the-box, and you don’t have to use the rest of the Spring framework for development. Another alternative is to utilize a third-party solution providing authentication and authorization services, such as Auth0

Be Careful with Error and Exception Handling

Error and exception messages can expose sensitive information such as configuration data and internal system components. For instance, a FileNotFoundException can reveal the file system layout, but even if the message is removed, the exception still tells whether the file exists. In addition, a stack trace may reveal information about technologies used in the development.

Therefore, sanitizing exception messages and types is necessary before passing them to end users.

Update the Runtime Quarterly

Quarterly Critical Patch Updates (CPUs) help developers to keep the Java runtime safe by promptly introducing security patches and minimizing risks of zero-day attacks.

If you don’t update the runtime regularly, your Java runtime harbors unpatched vulnerabilities making other security techniques you implement as good as useless. For example, 135 common vulnerabilities and exposures (CVEs) were identified and patched in JDK 11 within five years of its existence! 

What if you use free Java 6(7) builds that are no longer supported? If upgrading to a newer Java version is not an option, consider using Liberica JDK 6(7), which receives quarterly security updates and essential fixes like any other Liberica JDK version.

Harden your Container Images

A container is a cornerstone of cloud-native microservice development. But at the same time, it is the weakest link of a modern software supply chain. According to the Supply Chain Visibility & Risk Study by Netrise, a typical container image includes 604 known vulnerabilities on average, nearly half of them years old. The situation with Java services is particularly grave as 44% of Java services contain known-exploited vulnerabilities.

Therefore, containers must be as secure as any other component of the IT infrastructure.

Teams often neglect this issue, especially when they build containers on a random base image. This results in bloated container images with dozens of unused libraries, compilers, package managers, and nested with CVEs. That makes exploitation easier and the operational burden higher as teams have to spend resources on patching the code they didn’t even write.

Hardened images exist to eliminate the known failure modes of bloated, mutable containers: they strip the attack surface, contain low-to-zero CVEs by design, and are signed and attestable so SREs get a stable, auditable foundation.

Several vendors offer them. Pick one that owns OS and runtime security end to end, ships signed images with SBOMs and provenance, and continuously rebuilds with a published patch SLA.

For Java services, consider using BellSoft Hardened Images with first-class Java and Linux support and capabilities of in-house patching.

Implement A Software Bills of Materials (SBOM) 

A software bill of materials (SBOM) is a comprehensive inventory solution to identify vulnerabilities throughout the supply chain. SBOMs provide unmatched visibility into the project structure by listing all software components the program is made of, including direct and transitive dependencies, with essential data about them: supplier name, component name and version, present vulnerabilities, etc.

As such, an SBOM enables the developers to

  • Identify nested vulnerabilities,
  • Minimize risks of license violations,
  • Understand the state of dependencies (whether they are up to date or were abandoned two years ago).

Conclusion: How to Stay Up-to-date with Security Measures

Cybercriminals are getting bolder and craftier, but the good news is that security experts worldwide develop new techniques and measures aimed at repelling their attacks. Implementing them all may take time, so plan a step-by-step cybersecurity strategy, beginning with the most urgent tasks:

  • Implement vulnerability scanners and generate a software bill of materials for your project to gain understanding of the current security status of your infrastructure. From here, gradually substitute vulnerable libraries with safer solutions;
  • Transfer your cloud workloads to BellSoft Hardened Images to optimize resource consumption, eliminate licensing issues, and ensure the absence of CVEs in your project;
  • Implement the security practices described in this document and promote development processes with security as the core value;
  • Know cold the OWASP Top 10 security risks and recommendations on their prevention to promote safer coding practices in your team.

Subcribe to our newsletter

figure

Read the industry news, receive solutions to your problems, and find the ways to save money.

Further reading