· 9 years ago · Oct 28, 2016, 03:04 PM
1
2 import java.security.NoSuchAlgorithmException;
3
4 import javax.crypto.Cipher;
5 import javax.crypto.NoSuchPaddingException;
6 import javax.crypto.spec.IvParameterSpec;
7 import javax.crypto.spec.SecretKeySpec;
8
9 public class MCrypt {
10
11 private String iv = "TamTecIV";//Dummy iv (CHANGE IT!)
12 private IvParameterSpec ivspec;
13 private SecretKeySpec keyspec;
14 private Cipher cipher;
15
16 private String SecretKey = "TamTecArianGPSProject";//Dummy secretKey (CHANGE IT!)
17
18 public MCrypt()
19 {
20 ivspec = new IvParameterSpec(iv.getBytes());
21
22 keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
23
24 try {
25 cipher = Cipher.getInstance("AES/CBC/NoPadding");
26 } catch (NoSuchAlgorithmException e) {
27 // TODO Auto-generated catch block
28 e.printStackTrace();
29 } catch (NoSuchPaddingException e) {
30 // TODO Auto-generated catch block
31 e.printStackTrace();
32 }
33 }
34
35 public byte[] encrypt(String text) throws Exception
36 {
37 if(text == null || text.length() == 0)
38 throw new Exception("Empty string");
39
40 byte[] encrypted = null;
41
42 try {
43 cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
44
45 encrypted = cipher.doFinal(padString(text).getBytes());
46 } catch (Exception e)
47 {
48 throw new Exception("[encrypt] " + e.getMessage());
49 }
50
51 return encrypted;
52 }
53
54 public byte[] decrypt(String code) throws Exception
55 {
56 if(code == null || code.length() == 0)
57 throw new Exception("Empty string");
58
59 byte[] decrypted = null;
60
61 try {
62 cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
63
64 decrypted = cipher.doFinal(hexToBytes(code));
65 } catch (Exception e)
66 {
67 throw new Exception("[decrypt] " + e.getMessage());
68 }
69 return decrypted;
70 }
71
72
73
74 public static String bytesToHex(byte[] data)
75 {
76 if (data==null)
77 {
78 return null;
79 }
80
81 int len = data.length;
82 String str = "";
83 for (int i=0; i<len; i++) {
84 if ((data[i]&0xFF)<16)
85 str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
86 else
87 str = str + java.lang.Integer.toHexString(data[i]&0xFF);
88 }
89 return str;
90 }
91
92
93 public static byte[] hexToBytes(String str) {
94 if (str==null) {
95 return null;
96 } else if (str.length() < 2) {
97 return null;
98 } else {
99 int len = str.length() / 2;
100 byte[] buffer = new byte[len];
101 for (int i=0; i<len; i++) {
102 buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
103 }
104 return buffer;
105 }
106 }
107
108
109
110 private static String padString(String source)
111 {
112 char paddingChar = ' ';
113 int size = 16;
114 int x = source.length() % size;
115 int padLength = size - x;
116
117 for (int i = 0; i < padLength; i++)
118 {
119 source += paddingChar;
120 }
121
122 return source;
123 }
124 }