package com.yihu.jw.hospital.prescription.service.entrance.util;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.yihu.jw.utils.encode.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AES {

	public static String encrypt(String strKey, String strIn) {
		try {
			SecretKeySpec skeySpec = getKey(strKey);
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(
					"0102030405060708".getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			byte[] encrypted = cipher.doFinal(strIn.getBytes("UTF-8"));

			return Base64.encode(encrypted);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String decrypt(String strKey, String strIn) throws Exception {
		try {
			SecretKeySpec skeySpec = getKey(strKey);
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(
					"0102030405060708".getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = Base64.decode(strIn);

			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, "UTF-8");
			return originalString;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static SecretKeySpec getKey(String strKey) throws Exception {
		byte[] arrBTmp = strKey.getBytes();
		byte[] arrB = new byte[16]; // 创建一个空的16位字节数组（默认值为0）

		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}

		SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

		return skeySpec;
	}
	
	/** 
	 * 随机生成秘钥 
	 */  
	public static void generateKey(){    
	    try {    
	        KeyGenerator kg = KeyGenerator.getInstance("AES");    
	        kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256    
	        SecretKey sk = kg.generateKey();    
	        byte[] b = sk.getEncoded();    
	        String s = byteToHexString(b);    
	        System.out.println(s);    
	        System.out.println("十六进制密钥长度为"+s.length());    
	        System.out.println("二进制密钥的长度为"+s.length()*4);    
	    } catch (NoSuchAlgorithmException e) {    
	        e.printStackTrace();    
	        System.out.println("没有此算法。");    
	    }    
	} 
	
	/** 
	 * byte数组转化为16进制字符串 
	 * @param bytes 
	 * @return 
	 */  
	public static String byteToHexString(byte[] bytes){       
	    StringBuffer sb = new StringBuffer();       
	    for (int i = 0; i < bytes.length; i++) {       
	         String strHex=Integer.toHexString(bytes[i]);   
	         if(strHex.length() > 3){       
	                sb.append(strHex.substring(6));       
	         } else {    
	              if(strHex.length() < 2){    
	                 sb.append("0" + strHex);    
	              } else {    
	                 sb.append(strHex);       
	              }       
	         }    
	    }    
	   return  sb.toString();       
	}

	public static String signConvertToPara(String region) {
		String target = "";
		if (region != null) {
			target = region.replaceAll("\\+", "%2B").replaceAll("\\ ", "%20")
					.replaceAll("\\/", "%2F").replaceAll("\\?", "%3F")
					.replaceAll("\\#", "%23").replaceAll("\\&", "%26")
					.replaceAll("\\=", "%3D");
		}
		return target;
	}

	public static String paraConvertsign(String region) {
		String target = "";
		if (region != null) {
			target = region.replaceAll("%2B", "+").replaceAll("%20", " ")
					.replaceAll("%2F", "/").replaceAll("%3F", "?")
					.replaceAll("%25", "%").replaceAll("%23", "#")
					.replaceAll("%26", "&").replaceAll("%3D", "=");
		}
		return target;
	}
	//用于和c#互通的加解密
	//https://www.jianshu.com/p/9483c9ea3a04
	 /**
     * AES的加密函数
     * @param str 传入需要加密的字符
     * @param key 传入一个16位长度的密钥。否则报错
     * @return 执行成功返回加密结果，否则报错
     * @throws Exception 抛出一个加密异常
     */
    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }
    /**
     * AES的解密函数
     * @param str 传入需要解密的字符
     * @param key 传入一个16位长度的密钥。否则报错
     * @return 执行成功返回加密结果，否则报错
     * @throws Exception 抛出一个解密异常
     */
    public static String aesDecrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }
    
	public static void main(String[] args) throws Exception {
		generateKey();
		String testKey = "xmxzzxtj";
		String testEn = AES.encrypt(testKey, "{'function':'healthExam','yyid00':'220006','userId':'','name':'','phone':'','identityCard':'','icCard':''}");
		System.out.println(testEn);
		String testDe = AES.decrypt(testKey, testEn);
		System.out.println(testDe);
		

	}
}
