Standard Practice For Protecting Sensitive Data in Java Application
Last Updated :
21 Sep, 2021
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 formulas used to encode and decode messages are called encryption algorithms, or ciphers.
Let us do go through essentials, in brief, to get a better understanding of the standard practices for protecting sensitive data in Java applications.
- Encryption is a way of scrambling data so that only authorized parties can understand the information. In technical terms, It is the process of converting the human-readable plaintext to the incomprehensible text known as ciphertext.
- Decryption is taking encoded or encrypted text or other data and converting it back into the text so that you and the computer can understand.
- Cipher, any method of transforming a message to conceal its meaning. The term is also used synonymously with ciphertext or cryptogram in reference to the encrypted form of message.
- Secured Random class provides a cryptographically strong random number generator. A cryptographically strong random number minimally complies with statistical random number generator tests specified in FIPS 140-2, Security Requirements for cryptographic modules.
Example: SecureRandom class is used to generate a cryptographically strong pseudo-random number by using a PRNG Algorithm. The following are the advantages of using SecureRandom over Random. 1. SecureRandom produces a cryptographically strong pseudo-random number generator. 2. SecureRandom produces cryptographically strong sequences as described in RFC 1750: Randomness Recommendations for Security
Now let us come onto important methods of SecureRandom class
1. generateSeed() method returns the given number of seeds, computed using the seed generation.
Syntax:
generateSeed()
Return type: Byte array (returns the given number of seeds, computed using the seed generation).
2. setSeed() method reseeds the random object
Return type: Void
Example:
Java
// Java Program Demonstrating How Can We Get Secured
// Random Numbers from SecureRandom class
// Importing required classes
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try {
// Initialize a secure random number generator
SecureRandom secureRandom
= SecureRandom.getInstance("SHA1PRNG");
// Method 1
// Calling nextBytes method to generate Random
// Bytes
byte[] bytes = new byte[512];
secureRandom.nextBytes(bytes);
// Printing the SecureRandom number by
// calling secureRandom.nextDouble()
System.out.println(
" Secure Random # generated by calling nextBytes() is "
+ secureRandom.nextDouble());
// Method 2
// Using setSeed(byte[]) to reseed a Random
// object
int seedByteCount = 10;
byte[] seed
= secureRandom.generateSeed(seedByteCount);
secureRandom.setSeed(seed);
System.out.println(
" Secure Random # generated using setSeed(byte[]) is "
+ secureRandom.nextDouble());
}
// Catch block to handle the exceptions
catch (NoSuchAlgorithmException noSuchAlgo) {
// Display message if it occurs
System.out.println(" No Such Algorithm exists "
+ noSuchAlgo);
}
}
}
Output:
Secure Random # generated by calling nextBytes() is 0.8849167225465367
Secure Random # generated using setSeed(byte[]) is 0.7542495384908446
AES Encryption
AES-128 uses a 128-bit key length to encrypt and decrypt a block of messages, while AES -192 uses a 192-bit key length and AES-256 a 256-bit key length to encrypt and decrypt messages. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128,192 and 256 bits, respectively. Symmetric, also known as a secret key, ciphers use the same key for encrypting and decrypting, so the sender and the receiver must both know and use the same secret key.
ExampleÂ
Java
// Java Program to Illustrate AES Encryption
// Importing required classes
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
// Main class
class GFG {
// Encryption function
// function 1
public static void encryptEcb(String filenamePlain,
String filenameEnc,
byte[] key)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException
{
// Creating cipher instance OF AES encryption
Cipher cipher
= Cipher.getInstance("AES/ECB/PKCS5PADDING");
// Specifying the algorithm
SecretKeySpec secretKeySpec
= new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// Try block to check for exceptions
try (FileInputStream fis
= new FileInputStream(filenamePlain);
// Creating objects of BufferedInputStream,
// FileOutputStream and BufferedOutputStream
BufferedInputStream inputstream
= new BufferedInputStream(fis);
FileOutputStream outputstream
= new FileOutputStream(filenameEnc);
BufferedOutputStream bufferedOutputStream
= new BufferedOutputStream(outputstream)) {
// Defining the buffer
byte[] ibufffer = new byte[1024];
int length;
// Reading while read buffer has data
while ((length = inputstream.read(ibufffer))
!= -1) {
// Creating cipher with buffer
byte[] obuffer
= cipher.update(ibufffer, 0, length);
if (obuffer != null)
// Writing encrypted text to buffer
bufferedOutputStream.write(obuffer);
}
byte[] obuffer = cipher.doFinal();
if (obuffer != null)
bufferedOutputStream.write(obuffer);
}
}
// Method 3
// Decryption method
public static void decryptEcb(String filenameEnc,
String filenameDec,
byte[] key)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException
{
// Try block to check for exceptions
try (FileInputStream inputStream
= new FileInputStream(filenameEnc);
FileOutputStream outputStream
= new FileOutputStream(filenameDec)) {
// Defining buffer
byte[] ibuffer = new byte[1024];
int length;
// Creating cipher instance OF AES decryption
Cipher cipher = Cipher.getInstance(
"AES/ECB/PKCS5PADDING");
SecretKeySpec secretKeySpec
= new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// While input stream not empty
while ((length = inputStream.read(ibuffer))
!= -1) {
// Reading into the buffer
byte[] obuffer
= cipher.update(ibuffer, 0, length);
if (obuffer != null)
// Now writing to output buffer
outputStream.write(obuffer);
}
byte[] obuffer = cipher.doFinal();
if (obuffer != null)
outputStream.write(obuffer);
}
}
// Method 3
// Main driver method
public static void main(String[] args)
throws IOException, NoSuchPaddingException,
NoSuchAlgorithmException, BadPaddingException
,
IllegalBlockSizeException,
InvalidKeyException
{
// Display message
System.out.println("/****AES Encryption*******/");
// Placing the PDF path
String pFileName
= "/home/aniket/IdeaProjects/Gfg Programs/MAD FINAL.pdf";
String cFileName = "your pdf.enc";
// Placing the PDF name
String decFileName = "your pdf.pdf";
// Creating cipher key 56 bit key length
byte[] cipher_key
= "12345678901234561234567890123456".getBytes(
"UTF-8");
encryptEcb(pFileName, cFileName, cipher_key);
decryptEcb(cFileName, decFileName, cipher_key);
// Print and display the file credentials
System.out.println(
"file of encryption: " + pFileName + "\n"
+ "created encrypted file : " + cFileName
+ "\n"
+ "created decrypted file : " + decFileName);
}
}
Output:
/****AES Encryption*******/
file of encryption: MAD FINAL.pdf
created encrypted file : MAD FINAL.enc
created decrypted file : MAD FINAL.pdf
Similar Reads
Standard Practices for Protecting Sensitive Data in Java
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 smashi
4 min read
Understanding and Preventing SQL Injection in Java Applications
In the world of web applications and databases, security is paramount. SQL injection is a common and dangerous vulnerability that can compromise your application's integrity. In this article, we will delve into the fundamentals of SQL injection, understand how it works, and learn how to protect your
5 min read
PAC-RET Protection for Linux/AArch64 in Java
Pointer Authentication Codes (PAC) and Return Address Signing (RET) are security features available on certain ARM-based architectures, including AArch64. These features provide protection against control-flow attacks by ensuring the integrity of function return addresses. In this article, we will e
3 min read
Encrypting Sensitive Configuration Data in Spring Cloud Config
Encrypting sensitive configuration data in Spring Cloud Config is essential for securing information like passwords, API keys, and other credentials. This extra layer of protection is crucial because it helps prevent unauthorized access and ensures that sensitive data remains safe, even if the confi
4 min read
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, t
6 min read
How To Handle Sensitive Data In A Public Git Repo?
Managing sensitive data is one of the most important when working with public Git repositories. Whether you're developing software, collaborating on open-source projects, or deploying code to production environments, handling sensitive information like API keys, passwords, and configuration files re
9 min read
API Gateway Security Best Practices in Java Microservices
An API Gateway acts as a front-end for receiving API requests, enforcing throttling and security policies, passing requests to the back-end service, and then passing the response back to the requester. It sits between external clients and microservices, providing a unified entry point for multiple s
4 min read
Private vs Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by usi
5 min read
How to Setup Jackson in Java Application?
JSON(Javascript Object Notation) is the most popular format for the exchange of data in the world of web applications. The browsers can easily parse json requests and convert them to javascript objects. The servers parse json requests, process them, and generates a new json response. JSON is self-de
7 min read
Create a Simple Login Web Application with Encrypted Password in Java
Security is an important concept in any web application. We need to have the passwords stored in an encrypted way i.e. the passwords are not easily accessible by hackers or unauthorized users. Let's see a small demo application in this article using MySQL, Java, Servlet, and JSP technology. Step by
10 min read