How to Encrypt and Decrypt the Data by Using AES128

Posted By : Avnish Pandey | 31-Jul-2018

Need for data encryption and decryption :
If we want to integrate the third-party APIs with our application then we need to understand the concept of some algorithm which is provided in Java. Every third party APIs have own requirements for integrating them for security reasons and preventing some hacking attack. By using the algorithm which provided by java we can easily fulfill the requirements of third-party APIs and integrate them. Suppose, we are integrating any third party API. We have the requirement to encrypt the JSON and make the API call with the encrypted string and also we are getting the encrypted response then we need to decrypt the encrypted string for understanding the JSON response.

Encrypting and decrypting the data :
Here, we need the library for encrypting and decrypting the data. In Java, we got the libraries for the same. we got some classes 
in Java package like javax.crypto package for encrypting and decrypting the data. We are provided with some methods for doing encryption and decryption of the important data.

Here is an example for encrypting the data :

package com.service;

import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestParam;

public class Encryption {

	public String IVKey = "";
	public String secretKey = "";

	public String getEncryptedParam(@RequestParam Map<String, Object> paramMap) throws Exception {
		JSONObject parametersObject = new JSONObject();
		parametersObject.put("customerFirstName", "abc");
		parametersObject.put("customerLastName", "xyz");
		parametersObject.put("phoneNumber", "1234567890");
		parametersObject.put("address", "abc");
		byte[] encrypt = encryptString(parametersObject.toString(), secretKey, IVKey);
		String encryptedParams = bytesToHex(encrypt);
		return encryptedParams;

	}

	public static byte[] encryptString(String plainText, String secretKey, String IVKey) throws Exception {
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
		SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IVKey.getBytes("UTF-8")));
		return cipher.doFinal(padString(plainText).getBytes());
	}

	private static String padString(String source) {
		char paddingChar = ' ';
		int size = 16;
		int x = source.length() % size;
		int padLength = size - x;
		for (int i = 0; i < padLength; i++) {
			source += paddingChar;
		}
		return source;
	}

	public static String bytesToHex(byte[] data) {
		if (data == null) {
			return null;
		}
		int len = data.length;
		String string = "";
		for (int i = 0; i < len; i++) {
			if ((data[i] & 0xFF) < 16) {
				string = string + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
			} else {
				string = string + java.lang.Integer.toHexString(data[i] & 0xFF);
			}
		}
		return string;

	}
}

Here is the code for decrypting the encrypted data :

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Decryption {

	public String IVKey = "";
	public String secretKey = "";

	public static String decrypt(String encryptedString, String encryptionKey, String IVKey) throws Exception {
		byte[] cipherText = hexToBytes(encryptedString);
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
		SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
		cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IVKey.getBytes("UTF-8")));
		return new String(cipher.doFinal(cipherText), "UTF-8");
	}

	public static byte[] hexToBytes(String string) {
		if (string == null) {
			return null;
		} else if (string.length() < 2) {
			return null;
		} else {
			int len = string.length() / 2;
			byte[] buffer = new byte[len];
			for (int i = 0; i < len; i++) {
				buffer[i] = (byte) Integer.parseInt(string.substring(i * 2, i * 2 + 2), 16);
			}
			return buffer;
		}
	}
}

Thanks,

About Author

Author Image
Avnish Pandey

Avnish has a good knowledge in core & advance Java, Spring and Hibernate Framework. He loves to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..