package com.palmnest.application.core.util.wxpay;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 新大正支付AESUtils
 */
public class AesUtils {

    // 加密
    public static String Encrypt(String sSrc, String sKey) throws Exception {
    	if(StringUtils.isEmpty(sSrc)){
    		return "";
    	}
        if (sKey == null) {
        	throw new RuntimeException("秘钥异常");
        }
        // 判断Key是否为16位
        if (sKey.length()%16 != 0) {
        	throw new RuntimeException("秘钥异常");
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
 
        return Base64.encodeBase64URLSafeString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }
 
    // 解密
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
            	throw new RuntimeException("秘钥异常");
            }
            // 判断Key是否为16位
            if (sKey.length()%16 != 0) {
            	throw new RuntimeException("秘钥异常");
            }
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,"utf-8");
            return originalString;
        } catch (Exception e) {
        	throw e;
        }
    }
    
    public static String generateSecretKey() throws Exception{
    	String[] keyBase = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","e","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","E","S","T","U","V","W","X","Y","Z"};
    	StringBuffer key = new StringBuffer();
    	for (int i = 0; i < 32; i++) {
			int index = (int) (Math.random()*keyBase.length%keyBase.length);
			key.append(keyBase[index]);
		}
    	return key.toString();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(  AesUtils.Encrypt("","AD2A1B866750543DDC079D613273DF63"));
    }
}
