import CryptoJS from 'crypto-js'
import JsEncrypt from 'jsencrypt'
// import JsEncrypt from 'jsencrypt/bin/jsencrypt.min.js'
// 默认的 KEY 与 iv 如果没有给
const KEY = '1234567890ABCDEF';
const IV = '1234567890ABCDEF';
/** 
 * AES加密 ：字符串 key iv  返回base64
 */
export function EncryptECB(word, keyStr, ivStr) {
  let key = CryptoJS.enc.Utf8.parse(KEY);
  let iv = CryptoJS.enc.Utf8.parse(IV);
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }
  let srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    //iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  // console.log("-=-=-=-", encrypted.ciphertext)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
export function DecryptECB(word, keyStr, ivStr) {
  let key = CryptoJS.enc.Utf8.parse(KEY);
  let iv = CryptoJS.enc.Utf8.parse(IV);
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }
  let base64 = CryptoJS.enc.Base64.parse(word);
  let src = CryptoJS.enc.Base64.stringify(base64);
  var decrypt = CryptoJS.AES.decrypt(src, key, {
    //  iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}






/**
 * AES加密 ：字符串 key iv  返回base64
 */
export function EncryptCBC(word, keyStr, ivStr) {
  var key = CryptoJS.enc.Utf8.parse(KEY)
  var iv = CryptoJS.enc.Utf8.parse(IV)
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  var encrypted = CryptoJS.AES.encrypt(word, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  return encrypted.ciphertext.toString()
}
/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
export function DecryptCBC(word, keyStr, ivStr) {
  let key = CryptoJS.enc.Utf8.parse(KEY)
  let iv = CryptoJS.enc.Utf8.parse(IV)
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }
  var decrypt = CryptoJS.AES.decrypt(CryptoJS.format.Hex.parse(word), key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt)
}


export function getUUID() {
  return 'xxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16)
  });
}

export function EncryptRAS(word, publicKey) {
  let encry = new JsEncrypt();
  encry.setPublicKey(publicKey);
  let data = encry.encrypt(word);
  return data;
}
