· 9 years ago · Oct 10, 2016, 02:48 PM
1SecretKey aesKey = new SecretKeySpec(new byte[256 / Byte.SIZE], "AES");
2byte[] pt = "owlstead".getBytes(StandardCharsets.US_ASCII);
3
4{
5 // === CBC mode requires an IV of the same size as the block size
6 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
7 // changing the IV size will result in an exception
8 byte[] ivBytes = new byte[c.getBlockSize()];
9 IvParameterSpec iv = new IvParameterSpec(ivBytes);
10 c.init(Cipher.ENCRYPT_MODE, aesKey, iv);
11 byte[] ct = c.doFinal(pt);
12 System.out.println(Hex.toHexString(ct));
13}
14
15{
16 // === CTR mode actually requires a complete IV in Java
17 // Java (or actually, the SUN provider) requires a 128 bit IV instead of just a nonce
18 Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
19 // changing the IV size will result in an exception
20 byte[] ivBytes = new byte[c.getBlockSize()];
21 IvParameterSpec iv = new IvParameterSpec(ivBytes);
22 c.init(Cipher.ENCRYPT_MODE, aesKey, iv);
23 byte[] ct = c.doFinal(pt);
24 System.out.println(Hex.toHexString(ct));
25}
26
27{
28 // === GCM mode can do it!
29 Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
30 byte[] ivBytes = new byte[256 / Byte.SIZE];
31 GCMParameterSpec gcmSpecWithIV = new GCMParameterSpec(128, ivBytes);
32 c.init(Cipher.ENCRYPT_MODE, aesKey, gcmSpecWithIV);
33 byte[] ct = c.doFinal(pt);
34 System.out.println(Hex.toHexString(ct));
35}
36
37{
38 // === java.security.InvalidAlgorithmParameterException: ECB mode cannot use IV
39 Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
40 byte[] ivBytes = new byte[c.getBlockSize()];
41 IvParameterSpec iv = new IvParameterSpec(ivBytes);
42 c.init(Cipher.ENCRYPT_MODE, aesKey, iv);
43 byte[] ct = c.doFinal(pt);
44 System.out.println(Hex.toHexString(ct));
45}