Database encryption in Java
Last Updated :
02 Sep, 2020
Basically, encryption is the process or conversion of user data in code or more specifically in the cyphertext form in order to prevent unauthorized access, So, encryption is very much important in today's world where we all are working on large datasets stored in databases and the credentials of the database must be secured in order to secure the privacy and unauthorized access.
To encrypt our database credentials we will be using Jaspyt api. We can download the jaspyt library from here.
Java Simplified Encryption
Jasypt is a java library which allows the developer to add basic encryption capabilities to the projects with minimum effort, and without writing any code with the help of a few additions in your project here and there. Jasypt is highly configurable.
To encrypt database credentials we'll be doing these tasks-
- Create a POJO class.
- Create a properties file.
- Create a Java class.
Step 1: Creating a POJO class
So, we have created a Plain java class named Details.java having the actual username and actual password and the keys for username and password having special and non-special characters. The code as follows-
Java
// Creating a POJO class
package com.jdbc;
public class details {
// Private fields
private String key = "@2334dgdfg@#$%dsgdf";
private String user = "root";
private String key2 = "@1567sedf#2@";
private String pass = "root";
// Getter methods for private fields
public String getKey() { return key; }
public String getUser() { return user; }
public String getKey2() { return key2; }
public String getPass() { return pass; }
}
Step 2: Create an empty Properties file
Step 3- Create a MainConnecton class named TestJDBC2.java having all the lines of codes required for encryption and decryption process. We have used javax.crypto.Cipher Class, java.security.MessageDigest Abstract Class, org.jasypt.util.text.BasicTextEncryptor FinalClass which will be going to perform the encryption and decryption process.
So. First, we will going to use the key defined in the details.java file for encryption and decryption process of both username and password and will be going to call encrypt and decrypt method of BasicTextEncryptor class.
Now let's see the code-
Java
// Creating a java class
package com.jdbc;
import java.sql.Connection;
import java.io.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import org.jasypt.util.text.BasicTextEncryptor;
public class TestJdbc2 {
public static void main(String[] args)
throws ClassNotFoundException, SQLException,
IOException
{
// Fethches the system property
String path = System.getProperty("user.dir");
System.out.println("Working Directory = " + path);
// Creating a FileReader and specified the
// name of the file to read from
FileReader reader = new FileReader(
path + "/src/config.properties");
Properties p = new Properties();
// Reads a property list from the input byte stream
p.load(reader);
details dt = new details();
BasicTextEncryptor bte = new BasicTextEncryptor();
// Getting key from details class object and
// set the password for encryption and decryption
bte.setPassword(dt.getKey());
// Encrypt the message
String encryptedid = bte.encrypt(dt.getUser());
// Set the system property
p.setProperty("username", encryptedid);
BasicTextEncryptor bte1 = new BasicTextEncryptor();
// Setting a password
bte1.setPassword(dt.getKey2());
// Encrypt the password
String encryptedps = bte1.encrypt(dt.getPass());
p.setProperty("password", encryptedps);
// Writes the property list in the properties table
// to the output character stream in a format
// suitable for using load method
p.store(
new FileWriter(path + "/src/config.properties"),
" Properties Data");
// Load the driver class into the memory at the
// runtime
Class.forName("com.mysql.cj.jdbc.Driver");
// Establishes the connection and decrypt the
// encryptedid and encryptedps
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
bte.decrypt(encryptedid),
bte1.decrypt(encryptedps));
System.out.println("Connection successful!!!");
System.out.println("Done");
}
}
As can be seen the process of encryption and decryption clearly in this code. After the execution of this code, the encrypted username and password can be seen in the Config.properties file.
As Salt Algorithm processing can be clearly seen in the console process.
Now, let's have a look at the Config.properties file-
As the encrypted credentials can be seen clearly in the Config. Properties file and the original database credentials are in the details.java but the Connection properties are fetching the details from properties file in the encrypted form and decrypting the same to communicate with the database servers.
So now the database encryption is an easy task for all of us in Java.
Similar Reads
DSA in JAVA
Data Structures and Algorithms (DSA) are critical for optimizing how data is stored, accessed, and processed, directly affecting the performance of an application. This tutorial will guide you through the essential data structures and algorithms using the Java programming language.Why Learn DSA in J
14 min read
Mini Banking Application in Java
In any Bank Transaction, there are several parties involved to process transaction like a merchant, bank, receiver, etc. so there are several numbers reasons that transaction may get failed, declined, so to handle a transaction in Java, there is a JDBC (Java Database Connectivity) which provides us
7 min read
How to Extract Database Metadata using JDBC?
In JDBC, for extracting Metadata from the database we have one interface which is DatabaseMetaData. By using this interface, we can extract the metadata from the Database. We have a connection object It has getMetaData() method. After this, define the DatabaseMetaData and create an object for this.
8 min read
Java Collection Programs - Basic to Advanced
As it cleared from its name itself "Collection" it is a pre-defined collective bunch of classes and Interfaces present in the "Collection Framework" in Java. Their Classes, Interfaces and Methods are frequently used in competitive programming. This article provides a variety of programs on Java Coll
4 min read
Java Crash Course
In today's tech-driven world, coding is a valuable skill, and Java is an excellent starting point. Its versatility and ease of understanding make it ideal for a wide range of applications, from entertaining apps to crucial business tools. If you are new to coding or looking to expand your knowledge,
11 min read
Java Program to Insert Data from a Database to a Spread Sheet
A database is a persistent collection of data and information which is organized in a particular manner for quick access similarly spreadsheets are another way to store data in tabular form. There are two types of databases of which structured database particularly MySQL database is illustrated here
3 min read
How to Retrieve Database Information using Database Meta Data in JDBC?
JDBC (Java Database Connectivity) is the standard Java API for connecting and interacting with relational databases. It allowed to the Java applications to execute the SQL queries, retrieve the results, and perform the operations of the database in programmatically. In this article, we will learn to
3 min read
How to Create, Edit & Alter Tables Using Java?
In Java, JDBC can be used to create, edit, and alter the tables. JDBC can be defined as Java Database Connectivity. It is an API that allows Java programs to interact with the databases. JDBC can implement Java programs to execute SQL queries and manipulate databases through a standard interface. In
5 min read
JDBC Using Model Object and Singleton Class
In this article we will perform how to perform JDBC operations using a Model object and a Singleton connection class from a MySQL database. JDBC is an Application Programming Interface or Java which connects a Java application with a database to perform CRUD operations. Pre-requisite:JDK 7+ (Click h
6 min read
How to add Image to MySql database using Servlet and JDBC
Structured Query Language or SQL is a standard Database language which is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will understand how to add an image to the MYSQL database using servlet. MYSQL is a rel
6 min read