|
@@ -0,0 +1,65 @@
|
|
|
+// src/utils/crypto.ts
|
|
|
+import * as CryptoJS from 'crypto-js'
|
|
|
+
|
|
|
+/**
|
|
|
+ * AES加密工具类
|
|
|
+ * @description 使用CryptoJS实现数据加密/解密
|
|
|
+ * @reference https://cryptojs.gitbook.io/docs/
|
|
|
+ */
|
|
|
+class AESCipher {
|
|
|
+ private readonly key: CryptoJS.lib.WordArray
|
|
|
+ private readonly iv: CryptoJS.lib.WordArray
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 初始化加密类
|
|
|
+ * @param secretKey - 加密密钥(建议长度>=16位)
|
|
|
+ * @param ivStr - 初始向量(可选,默认与secretKey相同)
|
|
|
+ */
|
|
|
+ constructor(secretKey: string, ivStr?: string) {
|
|
|
+ this.key = CryptoJS.enc.Utf8.parse(secretKey)
|
|
|
+ this.iv = CryptoJS.enc.Utf8.parse(ivStr || secretKey.slice(0, 16))
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 加密数据
|
|
|
+ * @param data - 待加密数据
|
|
|
+ * @returns Base64编码的加密结果
|
|
|
+ */
|
|
|
+ encrypt(data: string): string {
|
|
|
+ const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data), this.key, {
|
|
|
+ iv: this.iv,
|
|
|
+ mode: CryptoJS.mode.CBC,
|
|
|
+ padding: CryptoJS.pad.Pkcs7
|
|
|
+ })
|
|
|
+ // 提取 ciphertext 并转为 Base64 [[1]]
|
|
|
+ return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 解密数据
|
|
|
+ * @param cipherText - 加密后的Base64字符串
|
|
|
+ * @returns 解密后的原始数据
|
|
|
+ */
|
|
|
+ decrypt(cipherText: string): string {
|
|
|
+ try {
|
|
|
+ // 先将 Base64 密文解析为 WordArray [[1]]
|
|
|
+ const cipherBytes = CryptoJS.enc.Base64.parse(cipherText)
|
|
|
+ // 转换为 Hex 格式(兼容 CryptoJS 解密逻辑)
|
|
|
+ const cipherWordArray = CryptoJS.format.Hex.parse(cipherBytes.toString())
|
|
|
+
|
|
|
+ const decrypted = CryptoJS.AES.decrypt(cipherWordArray, this.key, {
|
|
|
+ iv: this.iv,
|
|
|
+ mode: CryptoJS.mode.CBC,
|
|
|
+ padding: CryptoJS.pad.Pkcs7
|
|
|
+ })
|
|
|
+ return CryptoJS.enc.Utf8.stringify(decrypted) // 正确转换回字符串
|
|
|
+ } catch (error) {
|
|
|
+ console.error('Decryption failed:', error)
|
|
|
+ return ''
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+const key = import.meta.env.VITE_SECRET_KEY
|
|
|
+// 创建并导出单例实例
|
|
|
+const AesCipherInstance = new AESCipher(key) // 可以从环境变量中读取
|
|
|
+export default AesCipherInstance
|