· 7 years ago · Mar 03, 2018, 04:56 PM
1public class EncryptionUtils {
2
3 private MessageDigest dg = null;
4 private String username, password;
5 private byte[] key = null;
6
7 public EncryptionUtils(String username, String password) {
8 this.username = username;
9 this.password = password;
10 }
11
12 public String encode(String message) {
13 return byteArrayToString(getEncode(getKey(), message));
14 }
15
16 public String dencode(String message) {
17 try {
18 return new String(aes256Dec(getKey(), getEncode(getKey(), message)));
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 return "";
23 }
24
25 private byte[] getKey() {
26
27 if (key != null) {
28 return key;
29 }
30
31 try {
32 return hash(arrayMerge(username.getBytes(), hash(password.getBytes())));
33 } catch (Exception e) {
34 e.printStackTrace();
35 }
36 return new byte[]{0};
37 }
38
39 private byte[] getEncode(byte[] key, String message) {
40 try {
41 return aes256Enc(key, message.getBytes());
42 } catch (Exception e) {
43 e.printStackTrace();
44 }
45 return new byte[]{0};
46 }
47
48 private String byteArrayToString(byte[] bArr) {
49 return DatatypeConverter.printHexBinary(bArr);
50 }
51
52 public byte[] stringToByteArray(String str) {
53 return DatatypeConverter.parseHexBinary(str);
54 }
55
56 private byte[] arrayMerge(byte[] arr1, byte[] arr2) {
57 byte[] res = new byte[arr1.length + arr2.length];
58 System.arraycopy(arr1, 0, res, 0, arr1.length);
59 System.arraycopy(arr2, 0, res, arr1.length, arr2.length);
60 return res;
61 }
62
63 private byte[] hash(byte[] in) throws Exception {
64 if (dg == null)
65 dg = MessageDigest.getInstance("SHA-256");
66 return dg.digest(in);
67 }
68
69 private byte[] aes256Enc(byte[] key, byte[] in) throws Exception {
70 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
71 SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
72 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
73 return cipher.doFinal(in);
74 }
75
76 private byte[] aes256Dec(byte[] key, byte[] in) throws Exception {
77 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
78 SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
79 cipher.init(Cipher.DECRYPT_MODE, secretKey);
80 return cipher.doFinal(in);
81 }
82}