package com.jeequan.jeepay.thirdparty.channel.yspay.utils;


import hikefa.core.util.security.JDES;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author admin
 */
public class DesUtil {
	private static Log log = LogFactory.getLog(DesUtil.class);

	/**
	 * 备注：DES加密key只能�?8�?
	 * 加密扩展数据
	 * @param extraData
	 * @return
	 */
	public static String encryptExtraData(String key, String extraData) throws Exception {
		String out = "";
		String charset = "UTF-8";
		log.info("加密（前）数据：" + extraData);
		log.info("加密秘钥：" + key);
		try {
			if(StringUtils.isNotBlank(key)&&key.length()>8){
				key = key.substring(0,8);
			}
			JDES jd = new JDES();
			jd.SetKey(key.getBytes(charset));
			out = new String(Base64.encodeBase64(jd.doECBEncrypt(
					extraData.getBytes(charset),
					extraData.getBytes(charset).length)));
		} catch (Exception e) {
			log.error("进件参数加密异常", e);
		}
		log.info("加密（后）数据：" + out);
		return out;
	}

	/**
	 *
	 * @param key
	 * @param charset
	 * @param encryptExtraData
	 * @return
	 * @throws Exception
	 */
	public static String decryptExtraData(String key, String charset, String encryptExtraData)
			throws Exception {
		String out = "";
		log.info("解密（前）数据：" + encryptExtraData);
		log.info("解密秘钥：" + key);
		try {
			if(StringUtils.isNotBlank(key)&&key.length()>8){
				key = key.substring(0,8);
			}
			JDES jd = new JDES();
			jd.SetKey(key.getBytes(charset));
			byte[] encryptByte = Base64.decodeBase64(encryptExtraData);
			out = new String(jd.doECBDecrypt(encryptByte,
					encryptByte.length), charset);
		} catch (Exception e) {
			log.error(e, e);
		}
		log.info("解密（后）数据：" + out);
		return out;
	}
//
//	public static void main(String[] args)throws Exception {
//
//		String key = "A81F41DE7406CC1566579A751D93CA7A";
//		String charset = "UTF-8";//UTF-8\GBK
//		String str = "00#340103198907124036#银盛支付";
//		System.out.println("原�?�："+str+" , 字符集："+charset);
//		String d = DesUtil.encryptExtraData(key,charset,str);
//		System.out.println("加密�?"+d+" , 字符集："+charset);
//		String d1 = DesUtil.decryptExtraData(key,charset,d);
//		System.out.println("解密�?"+d1+" , 字符集："+charset);
//	}
}
