You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
2.5 KiB
107 lines
2.5 KiB
/**
|
|
* 加密工具类
|
|
* 包含 RSA 非对称加密和 AES 对称加密
|
|
*/
|
|
|
|
import CryptoJS from 'crypto-js'
|
|
import JSEncrypt from 'jsencrypt'
|
|
|
|
/**
|
|
* 生成随机字符串
|
|
* @param {number} length - 字符串长度
|
|
* @returns {string} 随机字符串
|
|
*/
|
|
export function randomStr(length) {
|
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
|
let result = ''
|
|
for (let i = 0; i < length; i++) {
|
|
result += chars.charAt(Math.floor(Math.random() * chars.length))
|
|
}
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* Base64 编码
|
|
* @param {string} str - 待编码字符串
|
|
* @returns {string} Base64编码后的字符串
|
|
*/
|
|
export function encodeBase64(str) {
|
|
return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str))
|
|
}
|
|
|
|
/**
|
|
* Base64 解码
|
|
* @param {string} str - Base64字符串
|
|
* @returns {string} 解码后的字符串
|
|
*/
|
|
export function decodeBase64(str) {
|
|
return CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8)
|
|
}
|
|
|
|
/**
|
|
* RSA 加密类
|
|
*/
|
|
export class RsaEncryption {
|
|
constructor({ publicKey, privateKey }) {
|
|
this.publicKey = publicKey
|
|
this.privateKey = privateKey
|
|
}
|
|
|
|
/**
|
|
* RSA 加密
|
|
* @param {string} data - 待加密数据
|
|
* @returns {string} 加密后的数据
|
|
*/
|
|
encrypt(data) {
|
|
const encryptor = new JSEncrypt()
|
|
encryptor.setPublicKey(this.publicKey)
|
|
return encryptor.encrypt(data) || ''
|
|
}
|
|
|
|
/**
|
|
* RSA 解密
|
|
* @param {string} data - 待解密数据
|
|
* @returns {string} 解密后的数据
|
|
*/
|
|
decrypt(data) {
|
|
const encryptor = new JSEncrypt()
|
|
encryptor.setPrivateKey(this.privateKey)
|
|
return encryptor.decrypt(data) || ''
|
|
}
|
|
}
|
|
|
|
/**
|
|
* AES 加密类
|
|
*/
|
|
export class AesEncryption {
|
|
/**
|
|
* AES 加密
|
|
* @param {string} data - 待加密数据
|
|
* @param {string} key - 加密密钥
|
|
* @returns {string} 加密后的数据
|
|
*/
|
|
encrypt(data, key) {
|
|
const keyHex = CryptoJS.enc.Utf8.parse(key)
|
|
const encrypted = CryptoJS.AES.encrypt(data, keyHex, {
|
|
mode: CryptoJS.mode.ECB,
|
|
padding: CryptoJS.pad.Pkcs7
|
|
})
|
|
return encrypted.toString()
|
|
}
|
|
|
|
/**
|
|
* AES 解密
|
|
* @param {string} data - 待解密数据
|
|
* @param {string} key - 解密密钥
|
|
* @returns {string} 解密后的数据
|
|
*/
|
|
decrypt(data, key) {
|
|
const keyHex = CryptoJS.enc.Utf8.parse(key)
|
|
const decrypted = CryptoJS.AES.decrypt(data, keyHex, {
|
|
mode: CryptoJS.mode.ECB,
|
|
padding: CryptoJS.pad.Pkcs7
|
|
})
|
|
return decrypted.toString(CryptoJS.enc.Utf8)
|
|
}
|
|
}
|