· 4 years ago · Sep 04, 2021, 04:08 PM
1 public static String encrypt(String secretKey, String content) {
2 try {
3 byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4 if (secretKey.length() > 0) iv = secretKey.substring(0,16).getBytes();
5 byte[] input = content.getBytes("utf-8");
6 byte[] sharedSecretKey = Base64.decode(SharedPrefOld.Companion.getInstance().getSharedSecretKey(), Base64.NO_WRAP);
7
8 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
9 cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sharedSecretKey, "AES"), new IvParameterSpec(iv));
10 byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
11 int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
12 cipher.doFinal(cipherText, ctLength);
13 return Base64.encodeToString(cipherText, Base64.NO_WRAP);
14
15 } catch (Exception e) {
16 e.printStackTrace();
17 return "";
18 }
19 }
20
21
22
23
24 public static String decrypt(String secretKey, String content) {
25 try {
26 byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
27 if (secretKey.length() > 0) iv = secretKey.substring(0,16).getBytes();
28 byte[] decodedCipherText = Base64.decode(content, Base64.NO_WRAP);
29 byte[] sharedSecretKey = Base64.decode(SharedPrefOld.Companion.getInstance().getSharedSecretKey(), Base64.NO_WRAP);
30 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
31 cipher.init(Cipher.DECRYPT_MODE,
32 new SecretKeySpec(sharedSecretKey, "AES"),
33 new IvParameterSpec(iv));
34 byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
35 return AppUtils.Companion.byteToString(decryptedBytes);
36
37 } catch (Exception e) {
38 e.printStackTrace();
39 return "";
40 }
41 }