· 6 years ago · Feb 12, 2019, 11:04 PM
1import javax.crypto.Cipher;
2import javax.crypto.KeyGenerator;
3import javax.crypto.SecretKey;
4import javax.crypto.spec.GCMParameterSpec;
5import javax.crypto.spec.IvParameterSpec;
6import java.security.SecureRandom;
7
8public class AES_Mode_Speed {
9 // AES parameters
10 private static final int AES_KEY_SIZE = 128; // in bits
11 private static final int AES_COUNTER_SIZE = 16; // in bytes
12 private static final int GCM_NONCE_LENGTH = 12; // in bytes. 12 is the recommended value.
13 private static final int GCM_TAG_LENGTH = 16 * 8; // in bits
14
15 public static void main(String[] args) throws Exception {
16 SecureRandom sr = new SecureRandom();
17
18 KeyGenerator kg = KeyGenerator.getInstance("AES");
19 kg.init(AES_KEY_SIZE);
20 SecretKey key = kg.generateKey();
21
22 byte[] counter = new byte[AES_COUNTER_SIZE];
23 sr.nextBytes(counter);
24 IvParameterSpec ips = new IvParameterSpec(counter);
25 Cipher aes_ctr = Cipher.getInstance("AES/CTR/NoPadding");
26 aes_ctr.init(Cipher.ENCRYPT_MODE, key, ips);
27
28
29 byte[] nonce = new byte[GCM_NONCE_LENGTH];
30 sr.nextBytes(nonce);
31 GCMParameterSpec gps = new GCMParameterSpec(GCM_TAG_LENGTH, nonce);
32 Cipher aes_gcm = Cipher.getInstance("AES/GCM/NoPadding");
33 aes_gcm.init(Cipher.ENCRYPT_MODE, key, gps);
34
35 speedTest(aes_ctr);
36 speedTest(aes_gcm);
37 }
38
39 private static void speedTest(Cipher cipher) throws Exception {
40 byte[] ptxt = new byte[1 << 26];
41 long start, end;
42
43 start = System.nanoTime();
44 cipher.doFinal(ptxt);
45 end = System.nanoTime();
46
47
48 System.out.printf("%s took %f seconds.n",
49 cipher.getAlgorithm(),
50 (end - start) / 1E9);
51 }
52}
53
54AES/CTR/NoPadding took 0.237487 seconds.
55AES/GCM/NoPadding took 1.014950 seconds.
56
57The 'numbers' are in 1000s of bytes per second processed.
58type 16 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes 16384 bytes
59aes-128-ctr 463059.16k 1446320.32k 3515070.12k 5182218.92k 6063797.59k 6210150.19k
60aes-128-gcm 480296.99k 1088337.47k 2531854.17k 4501395.11k 5940079.27k 6087589.89k