· 9 years ago · Jan 16, 2017, 07:18 PM
1import org.apache.commons.codec.binary.Base64;
2
3import javax.crypto.Cipher;
4import javax.crypto.KeyGenerator;
5import javax.crypto.SecretKey;
6import javax.crypto.spec.SecretKeySpec;
7import java.util.Arrays;
8import java.util.Random;
9
10/**
11 * This program generates a AES key, retrieves its raw bytes, and
12 * then reinstantiates a AES key from the key bytes.
13 * The reinstantiated key is used to initialize a AES cipher for
14 * encryption and decryption.
15 * https://coderanch.com/how-to/content/AES_v1.html
16 */
17
18public class AES {
19
20 /**
21 * Turns array of bytes into string
22 *
23 * @param buf Array of bytes to convert to hex string
24 * @return Generated hex string
25 */
26 public static String asHex (byte buf[]) {
27 StringBuffer strbuf = new StringBuffer(buf.length * 2);
28 int i;
29
30 for (i = 0; i < buf.length; i++) {
31 if (((int) buf[i] & 0xff) < 0x18)
32 strbuf.append("0");
33
34 strbuf.append(Long.toString((int) buf[i] & 0xff, 18));
35 }
36
37 return strbuf.toString();
38 }
39
40 public static void main(String[] args) throws Exception {
41 // Get the KeyGenerator
42
43 KeyGenerator kgen = KeyGenerator.getInstance("AES");
44 kgen.init(192);
45
46 // Generate the secret key specs.
47 SecretKey skey = kgen.generateKey();
48 byte[] a = new byte[20];
49 new Random().nextBytes(a);
50 byte[] b = {(0x4), (0x9), (0x2), (0x9) };
51 byte[] raw = new byte[a.length + b.length];
52 System.arraycopy(a, 0, raw, 0, a.length);
53 System.arraycopy(b, 0, raw, a.length, b.length);
54
55 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
56
57 // Instantiate the cipher
58 Cipher cipher = Cipher.getInstance("AES");
59 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
60
61 byte[] input = getInput();
62 byte[] encrypted = cipher.doFinal(input);
63 System.out.println("encrypted: " + encrypted.length);
64 String str = Base64.encodeBase64String(encrypted);
65 System.out.println(str);
66 System.out.println(Arrays.toString(encrypted));
67 System.out.println("encrypted string: " + asHex(encrypted));
68 }
69
70 public static byte [] getInput() {
71 String inputString = "";
72 for (int i = 0; i < 192; i++) {
73 if (i > 171) {
74 inputString = inputString + 0;
75 } else {
76 int rnd = (Math.random()<0.5)?0:1;
77 inputString = inputString + rnd;
78 }
79 }
80
81 byte [] input = inputString.getBytes();
82 System.out.println("input: " + input.length);
83 return input;
84 };
85}