· 7 years ago · Nov 13, 2018, 06:50 AM
1public static byte[] calculateMAC(byte[] _aiOutBufferForMacCalculation, String key) {
2 try{
3
4 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
5 SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
6 sha256_HMAC.init(secret_key);
7 byte[] mac_data=sha256_HMAC.doFinal(_aiOutBufferForMacCalculation);
8
9 String result = "";
10 for (final byte element : mac_data)
11 {
12 result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
13 }
14 System.out.println("Result:[" + result + "]");
15
16 return mac_data;
17 } catch (Exception _exception) {
18 _exception.printStackTrace();
19 }
20
21 public static byte[] hexStringToByteArray(String s) {
22 int len = s.length();
23 byte[] data = new byte[len / 2];
24 for (int i = 0; i < len; i += 2) {
25 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
26 + Character.digit(s.charAt(i+1), 16));
27 }
28 return data;
29}
30
31 public static void main(String[] args) {
32 String key = "7F6D7A688019DC4CA83883F2459E6B389BE99BB63B622A97";
33 String cadena = "1800990000014303181112190600048430303030303134370029030003483032001148324830303030303135320008143919751D5EB97C";
34
35
36 byte[] data_for_mac = hexStringToByteArray(cadena);
37
38 System.out.println(new String(data_for_mac));
39
40 byte[]mac = calculateMAC(data_for_mac,key);
41
42
43
44}
45
46}