xiejun
2023-09-21 52ffefd06e59cbd56c1a919972866592379cfed2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.vci.ubcs.starter.util;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
 
/**
 * @author ludc
 * @date 2023/9/20 11:08
 */
public class AESUtils {
 
    /**
     * aes加密
     * @param content 待加密数据
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String key) throws Exception {
        //指定加密算法
        Cipher cipher = Cipher.getInstance("AES");
        //创建加密规则:指定key和加密类型
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        //指定加密模式为加密,指定加密规则
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        //调用加密方法
        byte[] result = cipher.doFinal(content.getBytes());
        //用Base64编码
        return new String(Base64.getEncoder().encode(result));
    }
 
    /**
     * aes解密
     * @param content 待解密数据
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String content, String key) throws Exception {
        //Base64解码
        byte[] result = Base64.getDecoder().decode(content);
        //指定加密算法
        Cipher cipher = Cipher.getInstance("AES");
        //创建加密规则:指定key和加密类型
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        //指定加密模式为解密,指定加密规则
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return new String(cipher.doFinal(result));
    }
 
}