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; 
 | 
        } 
 | 
  
 | 
  
 | 
    } 
 |