import JSEncrypt from '@/components/jsencrypt/jsencrypt.min.js';
import cryptoJS from '@/crypto-js/index.js';

function generateRSAKeyPair() {
	const keySize = parseInt(1024);
	const encryptor = new JSEncrypt({
		default_key_size: keySize
	});

	encryptor.getKey();

	const publicKey = encryptor.getPublicKey();
	const privateKey = encryptor.getPrivateKey();
	console.log(publicKey, privateKey)
}
// rsa加密
export function rsaEncrypt(publicKey, data) {
	const encrypt = new JSEncrypt();
	encrypt.setPublicKey(publicKey);
	var time = +new Date();
	var str2 = data;
	return encrypt.encrypt(str2)
}
// ras解密
export function rsaDecrypt(PrivateKey, data) {
	const encrypt = new JSEncrypt();
	encrypt.setPrivateKey(PrivateKey);
	return encrypt.decrypt(data);
}
// aes加密
function aesEncrypt(data, key) {
	const iv = CryptoJS.lib.WordArray.random(16).toString() // 128位IV
	const encrypted = CryptoJS.AES.encrypt(
		JSON.stringify(data),
		CryptoJS.enc.Utf8.parse(key), {
			iv: CryptoJS.enc.Utf8.parse(iv),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		}
	)
	// console.log(encrypted)
	return {
		encryptedData: encrypted.toString(),
		iv
	}
}
// aes 解密函数
export function aesDecrypt(encryptedData, key, iv) {
	console.log(encryptedData, key, iv, '解密需要的参数')
	const decrypted = CryptoJS.AES.decrypt(
		encryptedData,
		CryptoJS.enc.Utf8.parse(key), {
			iv: CryptoJS.enc.Utf8.parse(iv),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		})
	return decrypted.toString(CryptoJS.enc.Utf8)
}
export default {
	generateRSAKeyPair,
	rsaEncrypt,
	rsaDecrypt,
	aesEncrypt,
	aesDecrypt
}