· 5 years ago · Sep 07, 2020, 08:56 AM
1package com.cyberviy.ViyP;
2
3import android.util.Log;
4
5import javax.crypto.Cipher;
6import javax.crypto.SecretKey;
7import javax.crypto.spec.SecretKeySpec;
8
9public class AESUtils
10{
11
12 private static final byte[] keyValue =
13 new byte[]{'v', 'i', 'y', 'p', 'b', 'y', 'v', 'u', 'l', 'n', 'r', 't', 'e', 'a', 'm', 's'};
14
15
16 public static String encrypt(String cleartext)
17 throws Exception {
18 byte[] rawKey = getRawKey();
19 byte[] result = encrypt(rawKey, cleartext.getBytes());
20 return toHex(result);
21 }
22
23 public static String decrypt(String encrypted)
24 throws Exception {
25 byte[] enc = toByte(encrypted);
26 byte[] result = decrypt(enc);
27 return new String(result);
28 }
29
30 private static byte[] getRawKey() throws Exception {
31 SecretKey key = new SecretKeySpec(keyValue, "AES");
32 byte[] raw = key.getEncoded();
33 return raw;
34 }
35
36 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
37 SecretKey skeySpec = new SecretKeySpec(raw, "AES");
38 Cipher cipher = Cipher.getInstance("AES");
39 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
40 byte[] encrypted = cipher.doFinal(clear);
41 return encrypted;
42 }
43
44 private static byte[] decrypt(byte[] encrypted)
45 throws Exception {
46 SecretKey skeySpec = new SecretKeySpec(keyValue, "AES");
47 Cipher cipher = Cipher.getInstance("AES");
48 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
49 byte[] decrypted = cipher.doFinal(encrypted);
50 return decrypted;
51 }
52
53 public static byte[] toByte(String hexString) {
54 int len = hexString.length() / 2;
55 byte[] result = new byte[len];
56 for (int i = 0; i < len; i++)
57 result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
58 16).byteValue();
59 return result;
60 }
61
62 public static String toHex(byte[] buf) {
63 if (buf == null)
64 return "";
65 StringBuffer result = new StringBuffer(2 * buf.length);
66 for (int i = 0; i < buf.length; i++) {
67 appendHex(result, buf[i]);
68 }
69 return result.toString();
70 }
71
72 private final static String HEX = "0123456789ABCDEF";
73
74 private static void appendHex(StringBuffer sb, byte b) {
75 sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
76 }
77}