xiaoyong931011
2023-10-25 0e7e1cfea951c7aee59a862c514e08a040523d9f
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
62
63
64
65
66
67
68
69
70
71
package cc.mrbird.febs.pay.util;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;
 
/**
 * AES加解密工具类
 * @author chenyf
 * @date 2018-12-15
 */
public class AESUtil {
    //   private static final Logger logger = LoggerFactory.getLogger(AesUtils.class);
        public static final String ALGORITHM = "AES/ECB/PKCS5Padding";
        public static final String UTF_8 = "UTF-8";
        public static final String AES = "AES";
        public static final String BC = "BC";
 
 
        static {
            //仅加载一次,不要多次加载,可能会导致内存溢出
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }
 
        /**
         * 网联敏感字段AES加密
         *
         * @param str 敏感字段原文
         * @param key AES密钥 必须是8位、16位、24位
         * @return
         */
        public static String Aes256Encode(String str, String key) {
          //  if(StringUtil.isNotBlank(str)) {
                try {
                    Cipher cipher = Cipher.getInstance(ALGORITHM, BC);
                    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(UTF_8), AES); // 生成加密解密需要的Key
                    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
                    byte[] result = cipher.doFinal(str.getBytes(UTF_8));
                    return Base64.getEncoder().encodeToString(result);
                } catch (Exception e) {
                   // logger.error("Aes256Encode error:", e);
                    return null;
                }
 
        }
 
        /**
         * 网联敏感字段密文解密
         *
         * @param base64Str 要被解密的密文.做了base64编码 base64Str
         * @param key       AES密钥 必须是8位、16位、24位
         * @return 解密后的字符串
         */
        public static String Aes256Decode(String base64Str, String key) {
           // if (StringUtil.isNotBlank(base64Str)) {
                String result = null;
                try {
                    Cipher cipher = Cipher.getInstance(ALGORITHM, BC);
                    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(UTF_8), AES); // 生成加密解密需要的Key
                    cipher.init(Cipher.DECRYPT_MODE, keySpec);
                    byte[] decoded = cipher.doFinal(Base64Util.decode(base64Str));
                    result = new String(decoded, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
        }
 
 
    }