· 7 years ago · Dec 21, 2018, 04:18 AM
1import javax.crypto.Cipher;
2import javax.crypto.spec.SecretKeySpec;
3import java.nio.charset.StandardCharsets;
4import java.util.Base64;
5
6public class AESEncryptor {
7
8 private static final byte[] key = "1234567890123456".getBytes(StandardCharsets.UTF_8);
9 private static final String ALGORITHM = "AES";
10
11 public static AESEncryptor instance = new AESEncryptor();
12
13 public String encrypt(String plainText) throws Exception {
14 return Base64.getEncoder().encodeToString(this.encrypt(plainText.getBytes(StandardCharsets.UTF_8)));
15 }
16
17 public String decrypt(String encText) throws Exception {
18 return new String(decrypt(Base64.getDecoder().decode(encText)), StandardCharsets.UTF_8);
19 }
20
21 private byte[] encrypt(byte[] plainText) throws Exception {
22 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
23 Cipher cipher = Cipher.getInstance(ALGORITHM);
24 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
25
26 return cipher.doFinal(plainText);
27 }
28
29 private byte[] decrypt(byte[] cipherText) throws Exception {
30 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
31 Cipher cipher = Cipher.getInstance(ALGORITHM);
32 cipher.init(Cipher.DECRYPT_MODE, secretKey);
33
34 return cipher.doFinal(cipherText);
35 }
36
37}