Given a message, We would like to encrypt & decrypt plain/cipher text using AES CBC algorithm in java. We will perform following operations:
- Generate symmetric key using AES-128.
- Generate initialization vector used for CBC (Cipher Block Chaining).
- Encrypt message using symmetric key and initialization vector.
- Decrypt the encrypted message using symmetric key and initialization vector.
Program to encrypt & decrypt message in java:
- Given encryption key & initialization vector.
- We will use AES algorithm to encrypt & decrypt input text.
- CryptoMngr is used generate cipher text from plain text & vice versa.
package org.learn; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class CryptoMngr { public static String ALGORITHM = "AES"; private static String AES_CBS_PADDING = "AES/CBC/PKCS5Padding"; public static byte[] encrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception { return CryptoMngr.encryptDecrypt(Cipher.ENCRYPT_MODE, key, IV, message); } public static byte[] decrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception { return CryptoMngr.encryptDecrypt(Cipher.DECRYPT_MODE, key, IV, message); } private static byte[] encryptDecrypt(final int mode, final byte[] key, final byte[] IV, final byte[] message) throws Exception { final Cipher cipher = Cipher.getInstance(AES_CBS_PADDING); final SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); final IvParameterSpec ivSpec = new IvParameterSpec(IV); cipher.init(mode, keySpec, ivSpec); return cipher.doFinal(message); } }
CryptoMngrClient Class: CryptoMngrClient class will generate random input message and will invoke CryptoMngr to encrypt & decrypt input message.
package org.learn; import java.util.Base64; import java.util.UUID; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class CryptoMngrClient { private static int AES_128 = 128; public static void main(String[] args) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(CryptoMngr.ALGORITHM); keyGenerator.init(AES_128); //Generate Key SecretKey key = keyGenerator.generateKey(); //Initialization vector SecretKey IV = keyGenerator.generateKey(); String randomString = UUID.randomUUID().toString().substring(0, 16); System.out.println("1. Message to Encrypt: " + randomString); byte[] cipherText = CryptoMngr.encrypt(key.getEncoded(), IV.getEncoded(), randomString.getBytes()); System.out.println("2. Encrypted Text: " + Base64.getEncoder().encodeToString(cipherText)); byte[] decryptedString = CryptoMngr.decrypt(key.getEncoded(), IV.getEncoded(), cipherText); System.out.println("3. Decrypted Message : " + new String(decryptedString)); } }
Program output to encrypt & decrypt to / from plain text is java:
1. Message to Encrypt: d6d0c0d9-a53c-42 2. Encrypted Text: hdZSyZiTq8t0FCifdgH0mqw0inpyZKLdGpbRgKjPUdA= 3. Decrypted Message : d6d0c0d9-a53c-42