无关风月
2024-11-26 5cf8494a6da08dfcdc5fdb4c5e55aefd8b27d684
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
53
54
55
56
57
58
59
60
61
package com.xinquan.common.core.utils;
 
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
public class EncryptUtils {
 
    private static final String SECRET = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
 
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
 
    /**
     * AES加密ECB模式PKCS7Padding填充方式
     *
     * @param str 字符串
     * @param key 密钥
     * @return 加密字符串
     * @throws Exception 异常信息
     */
    public static String aes256ECBPkcs7PaddingEncrypt(String str, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(doFinal));
    }
 
    /**
     * AES解密ECB模式PKCS7Padding填充方式
     *
     * @param str 字符串
     * @param key 密钥
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    public static String aes256ECBPkcs7PaddingDecrypt(String str, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(Base64.getDecoder().decode(str));
        return new String(doFinal);
    }
 
    public static void main(String[] args) throws Exception {
        String str = "a1234567";
        System.out.println("字符串:" + str);
        String encryptStr = EncryptUtils.aes256ECBPkcs7PaddingEncrypt(str, "AES454-HTJSQ9-IT");
        System.out.println("加密后字符串:" + encryptStr);
        String decryptStr = EncryptUtils.aes256ECBPkcs7PaddingDecrypt(encryptStr,
                "AES454-HTJSQ9-IT");
        System.out.println("解密后字符串:" + decryptStr);
    }
 
}