/* * Unrestricted security policy files for Java JRE need to be installed from Oracle for 256 keys to work */ package com.mycompany.mavenproject1; import java.security.SecureRandom; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; import java.util.Arrays; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class Main { private static final int keyLength = 32; private static final SecureRandom random = new SecureRandom(); private static SecretKey key; private static byte[] iv; public static void main(String [] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); String plaintext = "hello world"; byte [] ciphertext = encrypt(plaintext); String recoveredPlaintext = decrypt(ciphertext); System.out.println(recoveredPlaintext); } private static void printByteArr(byte[] arr) { System.out.print("["); for (int i = 0; i < arr.length; i++) { System.out.printf(i == 0 ? "%d" : ",%d", (arr[i] & 0xFF)); } System.out.println("]"); } private static byte [] encrypt(String plaintext) throws Exception { key = generateKey(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); String ivStr = "0123456789abcdef"; iv = ivStr.getBytes("US-ASCII"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); System.out.println( Base64.getEncoder().withoutPadding() .encodeToString(key.getEncoded()) ); printByteArr(iv); return cipher.doFinal(plaintext.getBytes()); } private static String decrypt(byte [] ciphertext) throws Exception { printByteArr(ciphertext); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); return new String(cipher.doFinal(ciphertext)); } private static SecretKey generateKey() throws Exception { byte[] keyBytes = new byte[keyLength]; random.nextBytes(keyBytes); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); return keySpec; } private static IvParameterSpec generateIV(Cipher cipher) throws Exception { byte [] ivBytes = new byte[cipher.getBlockSize()]; random.nextBytes(ivBytes); return new IvParameterSpec(ivBytes); } }