package com.allinpay.demo.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;


public class AESUtil {
	private static Log log = LogFactory.getLog(AESUtil.class);

	private static final String ENCODING = "GBK";
	private static final String KEY_ALGORITHM = "AES"; //密钥算法
	private static final String CRYPT_ALGORITHM = "AES/ECB/PKCS5Padding"; //加解密算法/工作模式/填充方式
	private static volatile String AES_KEY = null;

    static{
        if(Security.getProvider("BC") == null){
            BouncyCastleProvider prvd = new BouncyCastleProvider();  //密码不能用特殊符号
            Security.addProvider(prvd);
        }
    }
	
	public static String encrptWithBase64(String source, String key) throws Exception{
        Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM, "BC");// 创建密码器
        byte[] byteContent = source.getBytes(ENCODING);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化为加密模式的密码器
        byte[] result = cipher.doFinal(byteContent);// 加密
        return Base64.encodeBase64String(result);
	}
   

	public static String decryptWithBase64(String encryptedMsg, String key){
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM, "BC");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), KEY_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            //执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(encryptedMsg));
            return new String(result, ENCODING);
        } catch (Exception ex) {
            log.warn(ex.getMessage(), ex);
        }
        return encryptedMsg;
	}


}
