Wednesday, 12 July 2017

Encryption and Decryption using AES algorithm

We can see lot of encryption and decryption logic's available in Java, but where as Advanced Encryption Standard (AES) is one of most secured and symmetric encryption algorithm which is hard to crack and mostly used to encrypt sensitive but unclassified materials.
Encryption and Decryption using AES algorithm


Now lets see simple Java example how to use basic AES encryption and decryption.

import java.io.IOException;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

public class AESExample {

	private static final String key = "MySecretKey12345"; //Minimum 16 character
	private static final String AES = "AES";

	public static void main(String[] args) {
		
		String originalString = "Hello JavaDiscover"; // String to encrypt
		
		System.out.println("ORIGINAL STRING BEFORE ENCRYPTION ::: "+originalString);
		
		try {
			//Encryption
			String encryptedData = new AESExample().encrypt(originalString);
			
			System.out.println("ORIGINAL STRING AFTER ENCRYPTION ::: "+encryptedData);
			
			//Decryption
			String decryptedData = new AESExample().decrypt(encryptedData);
			
			System.out.println("ORIGINAL STRING AFTER DECRYPTION ::: "+decryptedData);

		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
				| BadPaddingException | IOException e) {
			e.printStackTrace();
		}
	}

	public String encrypt(String Data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey();
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] encVal = cipher.doFinal(Data.getBytes());
		@SuppressWarnings("restriction")
		String encryptedData = new BASE64Encoder().encode(encVal);
		return encryptedData;
	}

	public String decrypt(String encryptedData) throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey();
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		@SuppressWarnings("restriction")
		byte[] decDataByte = new BASE64Decoder().decodeBuffer(encryptedData);
		decDataByte = cipher.doFinal(decDataByte);
		String decryptedData = new String(decDataByte);
		return decryptedData;
	}

	private static Key generateKey() {
		Key myKey = new SecretKeySpec(key.getBytes(), AES);
		return myKey;
	}
}


OUTPUT:

ORIGINAL STRING BEFORE ENCRYPTION ::: Hello JavaDiscover
ORIGINAL STRING AFTER ENCRYPTION ::: aMHb8l4xLpwr/HuUQbLyIQdxSoLQ4Fc0sVRLzBEQoaQ=
ORIGINAL STRING AFTER DECRYPTION ::: Hello JavaDiscover

read more.. "Encryption and Decryption using AES algorithm"