Java Encrypt Decrypt Sample

What is encryption? The encryption process involves encoding a message or piece of information in a way that only authorized parties can access it and those who are not authorized cannot.

The Java Cipher class forms the functionality of a cryptographic cipher for encryption and decryption. This is the core of the Java Cryptographic Extension (JCE) framework.

One of the biggest uses of encryption and decryption in Java is when you want to protect a password. Having a password in plain text can be dangerous. In order to counteract this danger, we encrypt our password, store it somewhere, and decrypt is back when we need to use it.

The following sample sample is a very simple example of how to encrypt a String and then decrypt it back to its original text. I will go through each important piece and explain the purpose.

We define a cipher transformation, which uses the form algorithm/mode/padding. We defined an AES algorithm, ECB mode, and PKCS5Padding for the padding. AES algorithm is a 128 bit encryption method.

myAesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");


Calling the getInstnace() method of KeyGenerator will return a KeyGenerator object that we will use in the next step to generate a key.

KeyGenerator myKeyGenerator = KeyGenerator.getInstance("AES");


The generateKey() method will return a secret key to be used later.

myAesSecretKey = myKeyGenerator.generateKey();


This long line basically takes out secret key object and encodes it into a String using the Base64 class.

myAesKeyString = Base64.getEncoder().encodeToString(myAesSecretKey.getEncoded());


Now that we have our algorithm setup, we can now encrypt our plain text password String to make it secure. Start by setting mode to ENCRYPT_MODE, convert password String to byte array, and the doFinal() will return the encrypted password.

myAesCipher.init(Cipher.ENCRYPT_MODE, myAesSecretKey);
byte[] clearTextBuff = plainText.getBytes();
cipherTextBuff = myAesCipher.doFinal(clearTextBuff);	


Our password is encrypted, but what if we need to use the password? In order to use it, we will need to now decrypt it back to plain text. Start by decoding it using our key, generate a new secret key, set mode to DECRYPT_MODE, and again call doFinal() will return the decrypted password.

byte[] aesKeyBuff = Base64.getDecoder().decode(myAesKeyString);
SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");
myAesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
decipheredBuff = myAesCipher.doFinal(encryptedBytes);


The following code is the full source code to encrypt and decrypt in Java using a 128 bit AES encryption method. For even more security, we will do the same but using the AES 256 bit algorithm.


Java Encrypt Decrypt Sample Code

package com.jcd.java.tutorials;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class JavaAESEncryption 
{
	
	static Cipher myAesCipher;
	static String myAesKeyString;
	static SecretKey myAesSecretKey;
	

	public static void main(String[] args) 
	{
		String plainTextString = "JavaCodeDepot";
		
		System.out.println("Plain Text: "+plainTextString);
		
		setupCrypto();
		
		byte[] encryptedByteText = encryptAES(plainTextString);
		
		System.out.println("Encrypted Text: "+encryptedByteText.toString());
		
		String decryptedStringText = decryptAES(encryptedByteText);
		
		System.out.println("Decrypted Text: "+decryptedStringText);

	}
	
	public static void setupCrypto() 
	{
		try 
		{
			
			myAesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			
			KeyGenerator myKeyGenerator = KeyGenerator.getInstance("AES");
			    
			myAesSecretKey = myKeyGenerator.generateKey();
			    
			myAesKeyString = Base64.getEncoder().encodeToString(myAesSecretKey.getEncoded());
		}
		catch(Exception e)
		{
			System.out.println("Exception: "+e.toString());
		}
	}
	
	
	//Encrypt our string
	public static byte[] encryptAES(String plainText)
	{
		byte[] cipherTextBuff = null;
		
		try 
		{
			myAesCipher.init(Cipher.ENCRYPT_MODE, myAesSecretKey);
			
		    byte[] clearTextBuff = plainText.getBytes();
		    
		    cipherTextBuff = myAesCipher.doFinal(clearTextBuff);	
		}
		catch(Exception e)
		{
			System.out.println("encryptAES Exception: "+e.toString());
		}
		
		return cipherTextBuff;
		
	}
	
	//Decrypt our string
	public static String decryptAES(byte[] encryptedBytes) 
	{
		byte[] decipheredBuff = null;
		
		try 
		{
			byte[] aesKeyBuff = Base64.getDecoder().decode(myAesKeyString);
			
		    SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");

		    myAesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
		    
		    decipheredBuff = myAesCipher.doFinal(encryptedBytes);
		    
		}
		catch(Exception e)
		{
			System.out.println("decryptAES Exception: "+e.toString());
		}	
	    
		return new String(decipheredBuff);
	}

}


Java Encrypt Decrypt Sample Output

Plain Text: JavaCodeDepot
Encrypted Text: [B@66048bfd
Decrypted Text: JavaCodeDepot


Add a Comment

Your email address will not be published. Required fields are marked *