import CryptoJS from './crypto-js/crypto-js';

/**
 * 生成aes密匙
 * 生成规则：md5(当前时间戳 + 随机字符串)
 */
export const initAesKey = () => {
	return CryptoJS.MD5(new Date().getTime() + randomString(32)).toString();
}
/**
 * 接口数据加密函数
 * @param str string 需加密的json字符串
 * @param key_hash string 加密key_hash(16位)
 * @param iv string 加密向量(16位)
 * @return string 加密密文字符串
 */
export const aesEncrypt = (str, key_hash="s#e@5f98H*^his%t", _iv = '5e8y6w45ju8w9jq8') => {
	if(!str) {
		return str;
	}
	// console.log('str=>',str)
    //密钥
    var key = CryptoJS.enc.Utf8.parse(key_hash);
    //加密向量
    var iv = CryptoJS.enc.Utf8.parse(_iv);
    var encrypted = CryptoJS.AES.encrypt(str, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

export const aesEncrypt_HmacSha256 = (str, key_hash="s#e@5f98H*^his%t") => {
	if(!str) {
		return str;
	}

	var key = CryptoJS.enc.Utf8.parse(key_hash);
    var encrypted = CryptoJS.HmacSHA256(str, key);
	var hashInBase64 = CryptoJS.enc.Base64.stringify(encrypted);
    return hashInBase64;
}

/**
 * 接口数据解密函数
 * @param str string 已加密密文
 * @param key_hash string 加密key_hash
 * @param iv string 加密向量
 * @returns {*|string} 解密之后的json字符串
 */
export const aesDecrypt = (str, key_hash="s#e@5f98H*^his%t", iv = '5e8y6w45ju8w9jq8') => {
	if(!str) {
		return str;
	}

    //密钥
    var key = CryptoJS.enc.Utf8.parse(key_hash);

    //加密向量
    var iv = CryptoJS.enc.Utf8.parse(iv);
    var decrypted = CryptoJS.AES.decrypt(str, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}


function randomString(len) {
	len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = '';
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}
