1 import javax.crypto.Cipher;
2 import javax.crypto.spec.SecretKeySpec;
3 import java.nio.charset.StandardCharsets;
4 import java.util.Base64;
5
6 public class AESUtils {
7
8 private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
9
10 // 获取 cipher
11 private static Cipher getCipher(byte[] key, int model) throws Exception {
12 SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
13 Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
14 cipher.init(model, secretKeySpec);
15 return cipher;
16 }
17
18 // AES加密
19 public static String encrypt(byte[] data, byte[] key) throws Exception {
20 Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
21 return Base64.getEncoder().encodeToString(cipher.doFinal(data));
22 }
23
24 // AES解密
25 public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
26 Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
27 return cipher.doFinal(Base64.getDecoder().decode(data));
28 }
29
30 public static void main(String[] args) throws Exception {
31 //这个字符串就是钥匙,必须是个16位的字符串
32 String key = "1234567898765432";
33 byte[] kb = key.getBytes(StandardCharsets.UTF_8);
34 //加密
35 String encrypt = encrypt("要加密的内容".getBytes(StandardCharsets.UTF_8), kb);
36 System.out.println(encrypt);
37 //解密
38 byte[] decrypt = decrypt(encrypt.getBytes(StandardCharsets.UTF_8), kb);
39 System.out.println(new String(decrypt));
40 }
41 }