zy-vue-library/aesSecret/index.js

112 lines
3.3 KiB
JavaScript
Raw Normal View History

2025-10-22 11:19:51 +08:00
import CryptoJS from "crypto-js";
/**
* AES加密服务类
*/
class AESSecretService {
constructor() {
/**
* 默认配置
*/
this.config = {
key: "", // 加密密钥
encryptKey: "", // 加密解密密钥
decryptKey: "", // 加密密钥
};
}
/**
* 配置AES加密密钥
* @param {Object} config - 配置选项
* @param {string} [config.key] - 加密解密密钥
* @param {string} [config.encryptKey] - 加密密钥
* @param {string} [config.decryptKey] - 解密密钥
*/
configure(config) {
if (!config) throw new Error('配置不能为空');
if (!config.key && !config.encryptKey && !config.decryptKey) {
throw new Error('key、encryptKey、decryptKey 必须传入一个');
}
this.config = { ...this.config, ...config };
if (this.config.key) {
this.encryptKey = CryptoJS.enc.Utf8.parse(this.config.key);
this.decryptKey = CryptoJS.enc.Utf8.parse(this.config.key);
} else {
this.encryptKey = CryptoJS.enc.Utf8.parse(this.config.encryptKey);
this.decryptKey = CryptoJS.enc.Utf8.parse(this.config.decryptKey);
}
}
/**
* 加密方法
* @param {string|Object} word - 要加密的内容
* @returns {string} - 加密后的字符串
*/
encrypt(word) {
let encrypted = "";
if (typeof word === "string") {
const src = CryptoJS.enc.Utf8.parse(word);
encrypted = CryptoJS.AES.encrypt(src, this.encryptKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
} else if (typeof word === "object") {
// 对象格式的转成json字符串
const data = JSON.stringify(word);
const src = CryptoJS.enc.Utf8.parse(data);
encrypted = CryptoJS.AES.encrypt(src, this.encryptKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
}
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}
/**
* 解密方法
* @param {string} params - 要解密的内容
* @returns {string} - 解密后的字符串
*/
decrypt(params) {
const bytes = CryptoJS.AES.decrypt(params, this.decryptKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
const decryptedText = bytes.toString(CryptoJS.enc.Utf8);
return JSON.parse(decryptedText);
}
}
/**
* 配置AES加密服务
* @param {Object} config - 配置选项
* @param {string} [config.key] - 加密解密密钥
* @param {string} [config.encryptKey] - 加密密钥
* @param {string} [config.decryptKey] - 加密密钥
*/
export function configureAesSecret(config) {
if (!window.aesSecretService) window.aesSecretService = new AESSecretService();
return window.aesSecretService.configure(config);
}
/**
* 加密方法
* @param {string|Object} word - 要加密的内容
* @returns {string} - 加密后的字符串
*/
export function aesEncrypt(word) {
if (!window.aesSecretService) throw new Error('未配置AES加密服务请先调用 configureAesSecret');
return window.aesSecretService.encrypt(word);
}
/**
* 解密方法
* @param {string} params - 要解密内容
* @returns {string} - 解密后的字符串
*/
export function aesDecrypt(params) {
if (!window.aesSecretService) throw new Error('未配置AES加密服务请先调用 configureAesSecret');
return window.aesSecretService.decrypt(params);
}