import CryptoJS from 'crypto-js'
// @ts-ignore
import { JSEncrypt } from './jsencrypt'
const sysConfig = require('../../../public/config/sys-config.json')

// DES 解密
function decryptByDES (ciphertext: string, key: string) {
  const keyHex = CryptoJS.enc.Utf8.parse(key)
  const decrypted = CryptoJS.DES.decrypt(
    ({ ciphertext: CryptoJS.enc.Base64.parse(ciphertext) }) as any,
    keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export function decrypt (encrypted: any, DesKey: any) {
  const publicKey = sysConfig.publicKey
  const decrypt = new JSEncrypt()
  decrypt.setPublicKey(publicKey)
  const desKey = decrypt.decrypt(DesKey) // 解密
  const message = decryptByDES(encrypted.replace(/[\r\n]/g, ''), desKey)
  return JSON.parse(message)
}
