How to Write Secure Java Code: Avoiding Common Vulnerabilities
Jul 28, 2025 am 12:35 AMVerify and purify all inputs, use whitelist verification and OWASP Java Encoder to prevent XSS; 2. Prevent injection attacks, use parameterized queries to avoid SQL injection, and do not directly execute system commands entered by users; 3. Correctly handle authentication and session management, use strong hash algorithms such as bcrypt, and safely store session tokens; 4. Protect sensitive data, use AES-256 to encrypt data at rest, do not hardcode keys in the code, and promptly clear sensitive information in memory; 5. Avoid unsafe deserialization, and give priority to using secure data formats such as JSON; 6. Ensure dependency security, regularly update and scan third-party library vulnerabilities; 7. Implement secure error handling and logging, and do not expose internal details to users; 8. Follow the principle of minimal permissions and safely configure JVM and frameworks. In short, external input must be verified, purified and cannot be executed blindly to build defensive Java applications.
Writing secure Java code isn't about magic tricks—it's about being aware of common pitfalls and coding with defense in mind. Even experienced developers can introduce vulnerabilities by overlooking input validation, misusing APIs, or assuming trust where there is none. Below are key practices to avoid the most common security flaws in Java applications.

1. Validate and Sanitize All Input
Untrusted input is the root of many security issues, including injection attacks and denial-of-service vulnerabilities.
- Never trust user input , whether from web forms, APIs, files, or command-line arguments.
- Use whitelist validation (allow known good patterns) instead of blacklist approaches.
- For web apps, sanitize input to prevent Cross-Site Scripting (XSS) . Use libraries like OWASP Java Encoder when outputting data to HTML, JavaScript, or CSS.
- Validate length, type, format, and range. For example:
if (username == null || !username.matches("^[a-zA-Z0-9_]{3,20}$")) { throw new IllegalArgumentException("Invalid username"); }
Tip: Use frameworks like Spring with built-in validation annotations (
@NotBlank
,@Pattern
) to enforce constraints early.
2. Prevent Injection Attacks (SQL, OS, etc.)
SQL Injection remains a top risk when dynamic queries are built by string concatenation.
? Use parameterized queries or prepared statements :

String query = "SELECT * FROM users WHERE email = ?"; try (PreparedStatement stmt = connection.prepareStatement(query)) { stmt.setString(1, userEmail); ResultSet rs = stmt.executeQuery(); }
? Avoid:
// Dangerous! String query = "SELECT * FROM users WHERE email = '" userEmail "'";
For OS command injection , never pass user input directly to Runtime.exec()
or ProcessBuilder
. If unavoidable, validate strictly and use whitelisted commands.
Consider using safer APIs or libraries that abstract away direct command execution.
3. Handle Authentication and Session Management Properly
Weak auth mechanisms can expose your app to account takeover.
Use strong password hashing with algorithms like bcrypt , PBKDF2 , or Argon2 —never store plain text or use weak hashes like MD5/SHA-1.
// Example with BCrypt String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
Use secure session management:
- Regenerate session IDs after login.
- Set session timeout.
- Use secure, HttpOnly cookies for session tokens.
Integrate with proven frameworks like Spring Security instead of rolling your own auth logic.
4. Protect Sensitive Data
- Encrypt sensitive data at rest (eg, passwords, PII) using strong algorithms like AES-256.
- Use
javax.crypto
properly—avoid weak modes like ECB. Use authenticated encryption (eg, GCM mode). - Never hardcode secrets (passwords, API keys) in source code. Use environment variables or secure secret management tools (eg, Hashicorp Vault, AWS KMS).
- Clear sensitive data from memory when done:
char[] password = getPassword(); // use password Arrays.fill(password, '0'); // clear it
5. Avoid Insecure Deserialization
Deserializing untrusted data can lead to remote code execution .
- Avoid
ObjectInputStream
for untrusted sources. - If you must deserialize:
- Use
serialVersionUID
and validate classes. - Consider safer alternatives like JSON or XML with strict parsing (eg, Jackson, JAXB).
- Use libraries like SerialKiller to whitelist allowed classes.
- Use
Better yet: Use data transfer formats like JSON with POJO mapping instead of native Java serialization.
6. Secure Dependencies and Keep Libraries Updated
Many Java apps use third-party libraries (eg, Apache Commons, Jackson, Log4j). A vulnerable dependency can compensate your whole app.
- Use tools like OWASP Dependency-Check or Snyk to scan for known vulnerabilities.
- Regularly update dependencies.
- Remove unused libraries to reduce attack surface.
- Watch for critical flaws like Log4Shell (CVE-2021-44228) —they can lurk in transitive dependencies.
7. Apply Proper Error Handling and Logging
Revealing too much in error messages can aid attackers.
- Don't expose stack traces or internal details to users.
- Log errors securely on the server, but avoid logging sensitive data (passwords, tokens).
- Use a logging framework like SLF4J with Logback or Log4j2 (with security patches applied).
- Ensure logs are protected from unauthorized access.
8. Enforce Least Privilege and Secure Configuration
- Run your Java application with minimum OS/user privileges.
- Disable unwanted JVM features (eg, remote debugging in production).
- Set a SecurityManager (though deprecated in newer Java versions, still relevant in legacy systems).
- Harden
java.security
policy files when needed. - Disable unwanted endpoints in frameworks (eg, Actuator endpoints in Spring Boot).
Final Thoughts
Secure coding in Java doesn't require being a cryptography expert—it's about adopting defendive habits and using the right tools. Start by:
- Validating all inputs
- Using parameterized queries
- Managing secrets safely
- Keeping dependencies updated
- Leveraging security frameworks
Most vulnerabilities stem from known patterns. By following these practices and reviewing code with security in mind, you can drastically reduce risk.
Basically, if it comes from outside—verify it, sanitize it, and never execute it blindly.
The above is the detailed content of How to Write Secure Java Code: Avoiding Common Vulnerabilities. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C# is a widely used object-oriented programming language that is easy to learn, strongly typed, safe, reliable, efficient and has high development efficiency. However, C# programs may still be subject to malicious attacks or program errors caused by unintentional negligence. When writing C# programs, we should pay attention to the principles of safe programming and defensive programming to ensure the safety, reliability, and stability of the program. 1. Principles of secure programming 1. Do not trust user input. If there is insufficient verification in a C# program, malicious users can easily enter malicious data and attack the program.

Preventing man-in-the-middle attacks in Java Man-in-the-middle Attack is a common network security threat. An attacker acts as a man-in-the-middle to steal or tamper with communication data, making the communicating parties unaware of the communication between them. Being hijacked. This attack method may cause user information to be leaked or even financial transactions to be tampered with, causing huge losses to users. In Java development, we should also add corresponding defensive measures to ensure the security of communication. This article will discuss how to prevent

Preventing File Upload Vulnerabilities in Java File upload functionality is a must-have feature in many web applications, but unfortunately, it is also one of the common security vulnerabilities. Hackers can exploit the file upload feature to inject malicious code, execute remote code, or tamper with server files. Therefore, we need to take some measures to prevent file upload vulnerabilities in Java. Back-end verification: First, set the attribute that limits the file type in the file upload control on the front-end page, and verify the file type and

LDAP (Lightweight Directory Access Protocol) is a common network protocol used to access and manage directory services. In PHP language development, LDAP is often used to interact with external LDAP directory services, such as identity authentication and user authorization. However, due to the nature of LDAP, it also has some security vulnerabilities, such as LDAP injection and LDAP override issues. This article will explore how to avoid LDAP-related vulnerabilities in PHP language development. Avoid LDAP injection LDAP injection is a common security vulnerability, something like

Guide to Safe Programming Process and Vulnerability Repair in PHP Introduction: With the rapid development of the Internet, the security of web applications has attracted more and more attention. As a scripting programming language widely used in the field of web development, PHP also faces various security threats. This article will introduce the secure programming process in PHP and provide some code examples to help developers fix potential vulnerabilities. 1. Input validation In web applications, user input is the most vulnerable place. Therefore, the user's input must be verified first.

In PHP language development, it is very important to prevent the code from being used maliciously. Malicious attacks can cause user information to be stolen, network security to be destroyed, system operation to be interfered with, etc., so some measures must be taken to ensure the security of PHP code. This article will introduce some methods to prevent PHP code from being maliciously exploited. Filtering Input Data When writing PHP applications, user-supplied input data should always be treated as untrusted. Therefore, input data must be filtered and validated. PHP provides many filtering and validation functions, such as

How to carry out security protection and vulnerability scanning for Java development projects. With the rapid development of the Internet, Java development projects are becoming more and more widely used. However, due to the proliferation of network attacks and vulnerabilities, ensuring the security of Java development projects has become particularly important. This article will introduce how to perform security protection and vulnerability scanning of Java development projects to improve the security of the project. 1. Understand the common types of security vulnerabilities. Before performing security protection and vulnerability scanning on Java development projects, you first need to understand the common types of security vulnerabilities. Common Ja

Java developers can foster a culture of security and build secure applications by following best practices: Detect security vulnerabilities using static code analysis. Leverage security libraries such as encryption and authentication tools. Implement user input validation, checking expected formats and values. Follow established secure coding guidelines such as OWASPTop10. Continuous education to stay up to date on the latest security policies and threats.
