Newer
Older
xc-metering-front / src / utils / security.ts
liyaguang on 19 Jul 2023 1 KB first commit
/**
 * 加密工具类
 * Created by wangxiaoying 2022/11/17
 * **/
import JsEncrypt from 'jsencrypt'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

/**
  * RSA加密
  * @param value 待加密数据
  * @returns 加密结果
  */
export async function RSAencrypt(value: string): Promise<string> {
  const encrypt = new JsEncrypt()
  let enRes = ''
  if (userStore.getPublicKey && userStore.getPublicKey === '') {
    const res = await userStore.getBaseConfig()
    if (res && res.publicKey) {
      const publicKey = res.publicKey
      encrypt.setPublicKey(publicKey)// 从store中读取公钥
      enRes = encrypt.encrypt(value) || ''
    }
  }
  else {
    encrypt.setPublicKey(userStore.getPublicKey)// 从store中读取公钥
    enRes = encrypt.encrypt(value) || ''
  }
  return enRes
}
/**
 * 解密
 * @param value 待解密数据
 * @returns 解密结果
 */
export async function RSAdecrypt(value: string): Promise<string> {
  var encrypt = new JsEncrypt()
  let enRes = ''
  if (userStore.getPrivateKey && userStore.getPrivateKey === '') {
    const res = await userStore.getBaseConfig()
    if (res && res.privateKey) {
      const privateKey = res.privateKey
      encrypt.setPrivateKey(privateKey)
      enRes = encrypt.decrypt(value) || ''
    }
  }
  else {
    encrypt.setPrivateKey(userStore.getPrivateKey)
    enRes = encrypt.decrypt(value) || ''
  }
  return enRes
}