1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.crypto;
19
20 import java.nio.ByteBuffer;
21 import java.util.Properties;
22
23 import javax.crypto.Cipher;
24 import javax.crypto.spec.IvParameterSpec;
25 import javax.crypto.spec.SecretKeySpec;
26
27 import org.apache.commons.crypto.cipher.CryptoCipher;
28 import org.apache.commons.crypto.cipher.CryptoCipherFactory;
29 import org.apache.commons.crypto.random.CryptoRandom;
30 import org.apache.commons.crypto.random.CryptoRandomFactory;
31 import org.apache.commons.crypto.utils.AES;
32 import org.apache.commons.crypto.utils.Utils;
33
34 import static org.junit.jupiter.api.Assertions.assertEquals;
35
36 public abstract class AbstractBenchmark {
37
38 private static final byte[] KEY = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
39 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
40 private static final byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
41 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
42 private static final SecretKeySpec keySpec = Utils.newSecretKeySpec(KEY);
43 private static final IvParameterSpec ivSpec = new IvParameterSpec(IV);
44 private static final byte[] BUFFER = new byte[1000];
45
46 public AbstractBenchmark() {
47 super();
48 }
49
50 protected void random(final String cipherClass) throws Exception {
51 final CryptoRandom random = getRandom(cipherClass);
52 random.nextBytes(new byte[1000]);
53 random.nextBytes(new byte[1000]);
54 random.close();
55 }
56
57 protected void encipher(final String cipherClass) throws Exception {
58 final CryptoCipher enCipher = getCipher(cipherClass);
59 enCipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
60 final int bufferSize = 1024;
61 final ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
62 final ByteBuffer outBuffer = ByteBuffer.allocateDirect(bufferSize);
63 inBuffer.put(BUFFER);
64 inBuffer.flip();
65 enCipher.doFinal(inBuffer, outBuffer);
66 enCipher.close();
67 }
68
69 protected CryptoRandom getRandom(final String className) throws Exception {
70 final Properties props = new Properties();
71 props.setProperty(CryptoRandomFactory.CLASSES_KEY, className);
72 final CryptoRandom cryptoRandom = CryptoRandomFactory.getCryptoRandom(props);
73 assertEquals(className, cryptoRandom.getClass().getCanonicalName());
74 return cryptoRandom;
75 }
76
77 protected CryptoCipher getCipher(final String className) throws Exception {
78 final Properties properties = new Properties();
79 properties.setProperty(CryptoCipherFactory.CLASSES_KEY, className);
80 final CryptoCipher cipher = CryptoCipherFactory.getCryptoCipher(AES.CTR_NO_PADDING, properties);
81 assertEquals(className, cipher.getClass().getCanonicalName());
82 return cipher;
83 }
84
85 }