xiangpei
2025-04-18 ccadf9480d4e6a9dcc227a2a0b1f9ae0612e36fd
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
package com.monkeylessey.framework.service.cipher;
 
import org.springframework.stereotype.Service;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
 
/**
 * @author:xp
 * @date:2023/12/4 13:10
 */
@Service("AESCipherService")
public class AESCipherService extends DefaultCipherService {
 
    @Override
    public String decodeImpl(String cipherText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(getKey().getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(getIv().getBytes(StandardCharsets.UTF_8));
        // 指定算法器做解密操作
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
 
    @Override
    public String encodeImpl(String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 密文算法器(我瞎定义的),指定需要的算法
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 获取密钥对象
        SecretKeySpec keySpec = new SecretKeySpec(getKey().getBytes(StandardCharsets.UTF_8), "AES");
        // 获取增强随机对象
        IvParameterSpec ivSpec = new IvParameterSpec(getIv().getBytes(StandardCharsets.UTF_8));
        // 初始化算法器,第一个参数指定算法器做加密操作
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // 加密
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        // 将加密结果使用Base64编码可传给前端,使用Base64是因为默认的结果是乱码(结果就这样并不是有问题)的,编码后更清晰
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
}