· 7 years ago · Jun 28, 2018, 09:00 AM
1import java.security.SecureRandom;
2import java.util.Arrays;
3import javax.crypto.Cipher;
4import javax.crypto.SecretKey;
5import javax.crypto.spec.IvParameterSpec;
6
7
8 public static void main(String[] args) throws Exception {
9 //Generate a random AES Key
10 SecretKey key1 = generateAESKey();
11 byte[] plainText = "some plain text".getBytes();
12
13 //Gerate random IV
14 byte[] iv = new byte[16];
15 SecureRandom random = new SecureRandom();
16 random.nextBytes(iv);
17
18 //Encrypt plainText using the generated key1 using CTR
19 byte[] encryptedWithKey1 = encryptCTR(plainText, iv, key1);
20 //Now encrypt the IV using key1 with ECB
21 byte[] encryptedIvWithKey1 = encryptECB(iv, key1);
22
23 //Generate another key
24 SecretKey key2 = generateAESKey();
25 //First decrypt IV with wrong key, which resuts in wrong IV
26 byte[] decryptedIvWithKey2 = decryptECB(encryptedIvWithKey1, key2);
27 //Using this wrong IV decrypt encrypted payload with wrong key
28 byte[] decryptedWithKey2 = decryptCTR(encryptedWithKey1, decryptedIvWithKey2, key2);
29
30 //Expect plaintext and decrypted cipher using wrong key to NOT be equal
31 System.out.println("should print false: " + Arrays.equals(plainText, decryptedWithKey2));
32}
33
34 private static byte[] encryptCTR(byte[] plainText, byte[] iv, SecretKey key) throws Exception {
35 IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
36
37 Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
38 cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
39
40 return cipher.doFinal(plainText);
41}
42
43private static byte[] decryptCTR(byte[] encrypted, byte[] iv, SecretKey key) throws Exception {
44 IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
45
46 Cipher cipherDecrypt = Cipher.getInstance("AES/CTR/NoPadding");
47 cipherDecrypt.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
48 return cipherDecrypt.doFinal(encrypted);
49}
50
51private static byte[] encryptECB(byte[] plainText, SecretKey key) throws Exception {
52 Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
53 cipher.init(Cipher.ENCRYPT_MODE, key);
54
55 return cipher.doFinal(plainText);
56}
57
58private static byte[] decryptECB(byte[] encrypted, SecretKey key) throws Exception {
59 Cipher cipherDecrypt = Cipher.getInstance("AES/ECB/NoPadding");
60 cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
61 return cipherDecrypt.doFinal(encrypted);
62}
63 public static SecretKey generateAESKey() {
64 SecureRandom random = new SecureRandom();
65 byte[] keyBytes = new byte[16];
66 random.nextBytes(keyBytes);
67 SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
68 return key;
69}