The Wayback Machine - https://web.archive.org/web/20240914112624/https://www.geeksforgeeks.org/standard-practices-for-protecting-sensitive-data-in-java/
Open In App

Standard Practices for Protecting Sensitive Data in Java

Last Updated : 13 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Java platform provides an environment for executing code with different permission levels and a robust basis for secure systems through features such as memory safety. The Java language and virtual machine make application development highly resistant to common programming mistakes, stack smashing, and buffer overflow attacks which are possible in the C and C++ programming language. However, bugs produced through vulnerable programming practices can have serious security ramifications and could appear in any layer of the stack. In this article, we will list some standard programming practices in Java to protect sensitive data.

Secure coding guidelines contain the following parameters which are as follows:

  1. Releasing Resources
  2. Destroy sensitive information from exceptions
  3. Avoid Dynamic SQL
  4. Limiting Accessibility
  5. Limiting Extensibility

Let us discuss each of them how these practices do help in protecting our sensitive data in java and will be discussing with help of sample codes where ever required for better understandability.

1. Releasing Resources 

Application resources used during execution, such as open files, memory, objects, and locks if not released after their use could cause errors, duplication, and deadlocks during processing. Therefore, resources should always be released after their use by incorporating techniques like Execute Around Method (using lambda) and try-with-resource syntax.

Example 1: Illustrate Execute Around Methods

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Inserting code here

        // Execute Around pattern using Lambda
        // Clean-up is taken care of by lambda

        // Out lambda expression
        long sum = readFileBuffered(InputStream in -> {
            long current = 0;
            for (;;) {
                int b = in.read();
                if (b == -1) {
                    return current;
                }

                current += b;
            }
        });
    }
}

Example 2: Illustrating try-with-resources syntax

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Inserting code here

        // Try-with-resource syntax
        public R readFileBuffered(
            InputStreamHandler handler) throws IOException
        {

            // try statement with one or more resources
            try (final InputStream in
                 = Files.newInputStream(path)) {
                handler.handle(new BufferedInputStream(in));
            }

            // By now the resource is closed
            // at the end of the statement execution
        }
    }
}

2. Destroy sensitive information from exceptions

Many forms of attacks involve guessing or knowing the location of files, and exceptions may include sensitive information about the configuration and internals of the system. Stack traces of thrown exceptions such as java.io.FileNotFoundException can include the file paths of the system which can be used by attackers to backtrack to system files and target sensitive data. Therefore, internal exceptions should be caught and sanitized before propagating them to upstream callers.

3. Avoid Dynamic SQL

Dynamically created SQL statements from the untrusted sources can contain input that is subject to command injection, which means an injection of malicious code through SQL statements to directly affect data. Instead, parameterized SQL statements should be used such as java.sql.PreparedStatement or java.sql.CallableStatement so that the statements are pre-compiled and only parameters are needed to be inserted in order for them to execute.

Sample 

String sql = "SELECT * FROM User WHERE userId = ?"; 
PreparedStatement stmt = con.prepareStatement(sql); 
stmt.setString(1, userId); 
ResultSet rs = prepStmt.executeQuery();

4. Limiting Accessibility

Class members, methods, constructors, and interfaces should be declared as private or protected if they are not a part of an API to avoid exposing their implementation. If the implementations are encapsulated and not made public to outside entities then security is maintained as outsiders will not be able to change the internal structure.

5. Limiting Extensibility

If classes or methods are not declared final then an attacker can maliciously override them. A class that does not permit inheritance is easier to implement and verify that it is secure. Prefer composition to inheritance.

Example Limiting Extensibility through Composition and final class

// Class 1
// Helper class- Book class
class Book {

    // Member variables of Book class
    public String title;
    public String author;

    // Parameterized constructor of Book class
    Book(String title, String author)
    {
        // This refers to current object itself
        this.title = title;
        this.author = author;
    }
}

// Class 2
// Helper class
// Unsubclassable class Library with composed behavior.
public final class Library {

    // Composition
    private final List<Book> books;

    // Hiding the constructor of this class
    // by declaring it private
    private Library(Book book)
    {
        books = new ArrayList<Book>();
    }

    // Method of this class
    // Guarded Construction of class methods
    private void createLibrary(Book book)
    {
        // ...validate any arguments...

        // ...perform security checks...

        // adding elements to the book
        books.add(book);
    }
} 

In this article, we addressed some common pitfalls and the surrounding solutions. Hence, the most effective approach to minimizing vulnerabilities is to have obviously no flaws rather than no obvious flaws. These were some many practices that a Java programmer can adhere to in order to produce secure Java applications. 



Similar Reads

Standard Practice For Protecting Sensitive Data in Java Application
We can use encryption techniques to save our data. Encryption is the method by which information is converted into secret code that hides the information's true meaning. The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext. The
6 min read
Are Gmail Addresses Case Sensitive?
Like every other email address, Gmail address is a combination of two parts that are separated by the @ symbol. The part before @ is the username or local-part and the part after @ is the domain name or domain part. Both names may contain both upper-case and lower-case letters numbers, dots or periods, and underscores. Case sensitivity typically me
2 min read
10 Data Security Best Practices in 2024
In today's interconnected world, data is invaluable for both individuals and organizations. As data becomes more critical, ensuring its security has become a top priority to prevent breaches and unauthorized access. Effective data security is essential not only for protecting sensitive information but also for maintaining trust and compliance with
8 min read
Top 10 Best Practices for Data Migration
As an organization develops into a more data-driven commodity, investing in data migration becomes essential. With the ever-growing importance, type, and rate of data, outdated systems, software, and databases may no longer suffice. In such scenarios, data migration occurs as a crucial solution for organizations to adopt. Whether you're moving to a
13 min read
Best Practices For Automation Tester to Avoid Java Memory Leak Issue
A memory leak is a type of issue that will not cause any problem unless Java Heap Memory is overflown, but once you start getting this issue during execution, it’s very difficult to find out the root cause of it. So, it’s better to prevent memory leak issues in code from the very beginning. While building a test automation framework using Java, we
10 min read
Best Practices to Handle Exceptions in Java
Exception Handling is a critical aspect of Java programming, and following best practices for exception handling becomes even more important at the industry level where software is expected to be highly reliable, maintainable, and scalable. In this article, we will discuss some of the best practices for exception handling in Java that are relevant
7 min read
Java String Manipulation: Best Practices For Clean Code
In Java, a string is an object that represents a sequence of characters. It is a widely used data type for storing and manipulating textual data. The String class in Java is provided as a part of the Java standard library and offers various methods to perform operations on strings. Strings are fundamental to Java programming and find extensive usag
7 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
10 Best ReactJS Practices For a Good React Project
React is an Open-Source JavaScript library used to build (UIs)User Interfaces. It is the future of web creation with its extra versatility and ease. Since the release of React in 2013, it has gained so much popularity that the present React community count has increased to 56162. The industries count that has already adopted React has gone to 8787,
5 min read
7 React Best Practices Every Web Developer Should Follow
React...the most popular library of Javascript for building user interfaces. For developers, this library is one of the favorite libraries to build any kind of beautiful applications. Learning React might be easy for you. You start using React and you start developing an application. You create one component to build some features and then another
8 min read
Load Testing Basics, Tools &amp; Practices in Software Testing
Introduction: Load testing is a type of performance testing that simulates a real-world load on a system or application to see how it performs under stress. The goal of load testing is to identify bottlenecks and identify the maximum number of users or transactions the system can handle. Some popular tools for load testing include Apache JMeter, Lo
6 min read
5 Best Practices for Secure File Sharing
Businesses tend to thrive with the timely sharing of information or data. It is important for the organization to have access to the information that they need to accomplish their tasks, efficiently and conveniently. And that's why file-sharing is quite important to any business. Fortunately, technological advancement has made file sharing easy. Ho
4 min read
6 Best Practices to Perform a Cybersecurity Audit
Considering the rapid increment of cyber-attacks and vulnerabilities in the tech world, CyberSecurity seems to be only growing in demand!! Even as per the reports, most of the businesses have already disrupted in the last few years due to cybersecurity incidents. Moreover, if we take a look at a few prominent cybersecurity stats such as: The global
6 min read
Good Coding Practices For Backend Developers
API, Authentication, Design Patterns, MVC, Cache, Cookies, Sessions, JSON, Endpoints, Server, Hosting, Postman, CRUD, Curl... Aren't all these words familiar to you??? If yes, then surely you're a backend developer or working on the backend part of the application. Clients often underestimate the work of backend developers, especially those who onl
9 min read
Best Coding Practices For Rest API Design
JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a paym
10 min read
Best Git Practices to Follow in Teams
We all know that Git is one of the most popular version control used by developers all over the world. Developers are using it for many years but not all developers know the best practices for using it. There are several ways to use git to communicate with your team. You can use these git best practices from a small team of two to ten developers. W
6 min read
Best Practices to Write Clean Python Code
Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web developm
6 min read
5 Best Practices For Code Review
Software Development Process refers to implementing the design and operations of software, this process takes place which ultimately delivers the best product. Do several questions arise after this process like whether the code is secure? Is it well-designed? Is the code free of error? As per the survey, on average programmers make a mistake once a
6 min read
8 DevOps Best Practices That You Must Know
Developing software is a very tedious process. In a traditional company setup, the software development process is undertaken by two main teams i.e. the development team and the IT operations team. As expected, having two separate teams that work on a single project can cause internal frictions between the teams and hence slow down the overall depl
7 min read
Best Practices For Structuring Spring Boot Application
Spring Boot is built on top of the conventional spring framework. So, it provides all the features of spring and is yet easier to use than spring. In this article, we are going to see how one should start and structure his Spring Boot application. Prerequisites: Good knowledge of Java.Basic knowledge about Spring Boot.Basic knowledge about Creating
3 min read
7 Clean Coding Practices Developers Should Follow
Developers have this tendency to write efficient code but sometimes they lack clean coding practice. A good developer is one who writes code that is understandable by machines but the best developer writes code that is understandable by other developers. The code written should look good, clear, and understandable. Take a scenario where a developer
5 min read
10 Best Practices For Designing User Interfaces in Flutter
Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), and Web apps from a single codebase. When building applications with Flutter everything is towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch of material design-specific functionalitie
4 min read
Best Practices For Naming API Endpoints in a RESTful Architecture
Naming API endpoints is important in designing a clear and easy-to-use API. By using consistent and descriptive names, avoiding abbreviations, and following best practices for pluralization and lowercase letters, you can create an API that is easy to understand, use, and maintain. Naming API endpoints is an important part of designing a RESTful API
6 min read
10 Best Practices For Writing Documentation
Documentation is written data or instructions that outline a certain problem statement, approaches, functionality, workflow, architecture, challenges, and development process. Documentations can be used to gain a comprehensive understanding of the solution’s functionality, installation, and configurations at once. Writing good documentation holds i
9 min read
Best Practices of Object Oriented Programming (OOP)
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance , abstraction , polymorphism, and encapsulation in programming. The main aim of OOP is to bind together the data and the functions that operate on them so t
5 min read
Microservice Architecture - Introduction, Challenges & Best Practices
In software development, developers are following different approaches, technologies, architectural patterns, and best practices building the high quality software or the system. Microservice is one of the popular architectural pattern styles followed by the industries. You might have heard this name, and you might have worked on it. In a microserv
6 min read
Best SEO Practices For Writing Blogs
A collection of best practices is called Search Engine Optimization (SEO) which can raise your blog's position on search engine results pages like Google. To optimize your blog content for search engines, one has the option of linking that one can link to other websites and social media platforms and using popular keywords that readers of the inter
9 min read
Top 10 Cyber Security Best Practices For Businesses in 2024
Given the statistics, news reports, and possibly even your own past experiences, it's a no-brainer that businesses need adequate security measures in place to protect their data, assets, and operations against cyberattacks. Every person in a company, from end users to security professionals to executives, plays a part in protecting the company agai
7 min read
Top 10 Cloud Security Best Practices in 2024
In recent years the importance of security measures in organizations has been increasing rapidly. Hence organizations need cloud security so that these organizations can move towards a digital transformation strategy and incorporate cloud-based tools. As the organization's cloud adoption increases the business critical application and data migrate
7 min read
Best Practices For REST API Testing
REST, or Representational State Transfer, is a type of software architecture that is commonly used for building web services and APIs. A REST API is an application programming interface (API) that uses REST principles to expose data and functionality for client applications to access. REST APIs are typically based on the HTTP protocol and use HTTP
8 min read
Article Tags :
Practice Tags :