· 6 years ago · Sep 09, 2019, 05:16 AM
1package main;
2
3import java.security.spec.*;
4import javax.crypto.*;
5import javax.crypto.spec.*;
6
7class AESTest {
8 public static void main(String[] args) {
9 String test = "2";
10 try {
11 byte[] theKey = null;
12 byte[] theMsg = null;
13 byte[] theExp = null;
14
15 byte[] theIV = null;
16
17
18 System.out.println("AES-128: Pruebas \n");
19
20 for (int i = 0; i < 4; i++) {
21
22 System.out.println("Vector "+(i+1));
23 if (i == 0) {
24 theKey = hexToBytes("00000000000000000000000000000000");
25 theMsg = hexToBytes("9798c4640bad75c7c3227db910174e72");
26 theIV = hexToBytes("00000000000000000000000000000000");
27 theExp = hexToBytes("a9a1631bf4996954ebc093957b234589");
28 }
29
30 if (i == 1) {
31 theKey = hexToBytes("00000000000000000000000000000000");
32 theMsg = hexToBytes("96ab5c2ff612d9dfaae8c31f30c42168");
33 theIV = hexToBytes("00000000000000000000000000000000");
34 theExp = hexToBytes("ff4f8391a6a40ca5b25d23bedd44a597");
35 }
36
37 if (i == 2) {
38 theKey = hexToBytes("00000000000000000000000000000000");
39 theMsg = hexToBytes("cb9fceec81286ca3e989bd979b0cb284");
40 theIV = hexToBytes("00000000000000000000000000000000");
41 theExp = hexToBytes("92beedab1895a94faa69b632e5cc47ce");
42 }
43
44 if (i == 3) {
45 theKey = hexToBytes("00000000000000000000000000000000");
46 theMsg = hexToBytes("58c8e00b2631686d54eab84b91f0aca1");
47 theIV = hexToBytes("00000000000000000000000000000000");
48 theExp = hexToBytes("08a4e2efec8a8e3312ca7460b9040bbf");
49 }
50
51 SecretKeySpec secretKey = new SecretKeySpec(theKey, "AES");
52 Cipher cf = Cipher.getInstance("AES/CBC/NOPADDING");
53 cf.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(theIV));
54 byte[] theCph = cf.doFinal(theMsg);
55
56 System.out.println("Key : " + bytesToHex(theKey));
57 System.out.println("Message : " + bytesToHex(theMsg));
58 System.out.println("Cipher : " + bytesToHex(theCph));
59 System.out.println("Expected: " + bytesToHex(theExp));
60
61 System.out.println("");
62 }
63
64 } catch (Exception e) {
65 e.printStackTrace();
66 return;
67 }
68 }
69
70 public static byte[] hexToBytes(String str) {
71 if (str == null) {
72 return null;
73 } else if (str.length() < 2) {
74 return null;
75 } else {
76 int len = str.length() / 2;
77 byte[] buffer = new byte[len];
78 for (int i = 0; i < len; i++) {
79 buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
80 }
81 return buffer;
82 }
83
84 }
85
86 public static String bytesToHex(byte[] data) {
87 if (data == null) {
88 return null;
89 } else {
90 int len = data.length;
91 String str = "";
92 for (int i = 0; i < len; i++) {
93 if ((data[i] & 0xFF) < 16)
94 str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
95 else
96 str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
97 }
98 return str.toUpperCase();
99 }
100 }
101}