· 7 years ago · Jul 11, 2018, 01:10 PM
1package sort;
2
3import javax.crypto.Cipher;
4import javax.crypto.SecretKey;
5import javax.crypto.spec.SecretKeySpec;
6
7public class Bluetooth {
8
9 private static String key = "3A60432A5C01211F291E0F4E0C132825";
10 private static String msg = "060101012D1A683D48271A18316E471A";
11 private static String encMsg = "28BF68EB5D3334C8613762E87706F9FE";
12
13 public static void main(String[] args) {
14
15
16 byte msgHex[] = hexStringToByteArray(msg);
17 byte keyHex[] = hexStringToByteArray(key);
18
19 byte encryptedByte[] = encrypt(msgHex, keyHex);
20
21 System.out.println("String from encryptedByte = " + convertByteToString(encryptedByte));
22 System.out.println("Hex string from encryptedByte = " + getHex(encryptedByte));
23
24 byte encHex[] = hexStringToByteArray(encMsg);
25
26 byte decryptedByte[] = decrypt(encHex, keyHex);
27 String decString = getHex(decryptedByte);
28 System.out.println("decryptedByte to hexString = " + decString);
29
30 // msg and decString not matched.
31
32 }
33
34 public static byte[] decrypt(byte[] src, byte[] key) {
35 try {
36 SecretKey secretKey = new SecretKeySpec(key, "AES");
37 Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
38 cipher.init(Cipher.DECRYPT_MODE, secretKey);
39 byte[] decrypt = cipher.doFinal(src);
40 return decrypt;
41 } catch (Exception ex) {
42 System.out.println("Dec exception " + ex.getCause());
43 ex.printStackTrace();
44 return null;
45 }
46 }
47
48 public static byte[] encrypt(byte[] src, byte[] key) {
49 try {
50 SecretKey secretKey = new SecretKeySpec(key, "AES");
51
52 Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//("AES/ECS/NoPadding");
53 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
54 byte[] decrypt = cipher.doFinal(src);
55 return decrypt;
56 } catch (Exception ex) {
57 System.out.println("enc exception " + ex.getCause());
58 ex.printStackTrace();
59 return null;
60 }
61 }
62
63 public static String convertByteToString(byte[] by) {
64 try {
65 if (by != null && by.length > 0) {
66 String roundTrip = new String(by, "UTF8");
67 return roundTrip;
68 } else {
69 System.out.println("byte array is null");
70 }
71 } catch (Exception ex) {
72 System.out.println("exception aya = " + ex.getCause());
73 }
74
75 return "";
76 }
77
78 public static byte[] hexStringToByteArray(String s) {
79 int len = s.length();
80 byte[] data = new byte[len / 2];
81 for (int i = 0; i < len; i += 2) {
82 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
83 + Character.digit(s.charAt(i + 1), 16));
84 }
85
86 return data;
87 }
88
89
90 public static String getHex(byte b[]) {
91 StringBuffer result = new StringBuffer();
92 for (byte bk : b) {
93 result.append(String.format("%02X ", bk));
94 result.append(" "); // delimiter
95 }
96 return result.toString();
97 }
98
99}