import { JSEncrypt } from 'jsencrypt'
import CryptoJS from 'crypto-js'

export function encryptRSA(data, publicKey) {
  // 新建JSEncrypt对象
  const encryptor = new JSEncrypt()
  // 设置公钥
  encryptor.setPublicKey(publicKey)
  // 加密数据
  return encryptor.encrypt(data)
}

export function encryptAES(word, publicKey) {
  if (!publicKey) {
    publicKey = '0123456789101112'
  }
  var key = cryptToHex(publicKey.substr(0, 8))
  var iv = cryptToHex(publicKey.substr(publicKey.length - 8, 8))
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.ciphertext.toString().toUpperCase()
}

export function decryptAES(word, publicKey) {
  if (!publicKey) {
    publicKey = '0123456789101112'
  }
  var key = cryptToHex(publicKey.substr(0, 8))
  var iv = cryptToHex(publicKey.substr(publicKey.length - 8, 8))
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word)
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  var decrypt = CryptoJS.AES.decrypt(srcs, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

function cryptToHex(str) {
  var val = ''
  for (var i = 0; i < str.length; i++) {
    var temp = (str.charCodeAt(i) ^ 158).toString(16)
    if (temp.length === 1) {
      val += '0'
    }
    val += temp
  }
  return val
}
