import { encryptedData as encryptedDataRsa, decryptedData as decryptedDataRsa } from './rsa'
import { Base64 } from 'js-base64'
const NodeRSA = require('node-rsa')// 私钥加密 公钥解密

import { getKey } from '@/utils/auth'

// const Base64 = require('js-base64').Base64

// import { safety } from '@/api/login'
// 用于加密密钥的

// const keyPair = {}
// var serverKey = ''
// const begin = '-----BEGIN PUBLIC KEY-----'
// const end = '-----END PUBLIC KEY-----'
/**
 * 数据加密 公钥加密私钥解密
 * @param {Object} data 需要加密的数据
 */
export function encryptData(data) {
  if (!data) return data
  // data = Base64.encode(data)

  const keyInfo = JSON.parse(getKey())
  data = encryptedDataRsa(data, keyInfo.rsaPublicKey)

  return data
}

/**
 * 数据解密  公钥加密私钥解密
 * @param {Object} encrypts 需要解密的数据
 */
export function decryptData2(encrypts) {
  if (!encrypts) return ''
  const keyInfo = JSON.parse(getKey())

  encrypts = decryptedDataRsa(encrypts, keyInfo.rsaPublicKey)
  encrypts = Base64.decode(encrypts)

  return encrypts
}

// 解密 私钥加密后 公钥解密
export function decryptData(data) {
  if (!data) return ''
  const keyInfo = JSON.parse(getKey())
  const privateKey = '-----BEGIN PUBLIC KEY-----\n' + keyInfo.rsaPublicKey + '\n-----END PUBLIC KEY-----'

  try {
    const nodersa2 = new NodeRSA(privateKey)
    const decrypted2 = nodersa2.decryptPublic(data, 'utf8')
    // decrypted2 = Base64.decode(decrypted2)
    return decrypted2
  } catch (error) {
    return ''
  }
}
