encrypt.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import CryptoJS from 'crypto-js'
  2. import JSEncrypt from 'jsencrypt'
  3. const publicKey = atob(import.meta.env.VITE_RSA_PUBLIC_KEY)
  4. // 生成随机 AES 密钥
  5. export function generateAesKey(length = 16) {
  6. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  7. let key = ''
  8. for (let i = 0; i < length; i++) {
  9. key += chars.charAt(Math.floor(Math.random() * chars.length))
  10. }
  11. return key
  12. }
  13. // AES 加密
  14. export function aesEncrypt(data, key) {
  15. return CryptoJS.AES.encrypt(JSON.stringify(data), CryptoJS.enc.Utf8.parse(key), {
  16. mode: CryptoJS.mode.ECB,
  17. padding: CryptoJS.pad.Pkcs7
  18. }).toString()
  19. }
  20. export function aesDecrypt(encryptedData, aesKey) {
  21. const bytes = CryptoJS.AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(aesKey), {
  22. mode: CryptoJS.mode.ECB,
  23. padding: CryptoJS.pad.Pkcs7
  24. })
  25. return JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
  26. }
  27. // RSA 加密 AES 密钥
  28. export function rsaEncryptKey(aesKey) {
  29. const encryptor = new JSEncrypt()
  30. encryptor.setPublicKey(publicKey)
  31. return encryptor.encrypt(aesKey)
  32. }