· 5 years ago · May 20, 2020, 12:16 PM
1package com.lukichova.olenyn.app.classes;
2
3import javax.crypto.Cipher;
4import javax.crypto.spec.SecretKeySpec;
5import java.security.MessageDigest;
6import java.util.Arrays;
7import java.util.Base64;
8
9public class AES {
10 public static final String algorithm = "AES";
11 private static SecretKeySpec secretKey;
12 private static byte[] key;
13 private static String secret = "123";
14
15 public static void initKet() throws Exception {
16 if (key == null) {
17 MessageDigest sha = null;
18 key = secret.getBytes("UTF-8");
19 sha = MessageDigest.getInstance("SHA-1");
20 key = sha.digest(key);
21 key = Arrays.copyOf(key, 16);
22 secretKey = new SecretKeySpec(key, algorithm);
23 }
24 }
25
26 public static String encrypt(String strToEncrypt) throws Exception {
27 initKet();
28 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
29 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
30 return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
31 }
32
33 public static String decrypt(String strToDecrypt) throws Exception {
34 initKet();
35 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
36 cipher.init(Cipher.DECRYPT_MODE, secretKey);
37 return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
38 }
39}