2026-01-16 13:06:44 +08:00
|
|
|
import CryptoJS from 'crypto-js'
|
2026-01-20 10:58:42 +08:00
|
|
|
/**
|
|
|
|
|
* 加密解密工具类
|
|
|
|
|
*/
|
2026-01-16 13:06:44 +08:00
|
|
|
export class Crypto<T extends object> {
|
|
|
|
|
/** Secret */
|
|
|
|
|
secret: string
|
|
|
|
|
|
|
|
|
|
constructor(secret: string) {
|
|
|
|
|
this.secret = secret
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
encrypt(data: T): string {
|
|
|
|
|
const dataString = JSON.stringify(data)
|
|
|
|
|
const encrypted = CryptoJS.AES.encrypt(dataString, this.secret)
|
|
|
|
|
return encrypted.toString()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
decrypt(encrypted: string) {
|
|
|
|
|
const decrypted = CryptoJS.AES.decrypt(encrypted, this.secret)
|
|
|
|
|
const dataString = decrypted.toString(CryptoJS.enc.Utf8)
|
|
|
|
|
try {
|
|
|
|
|
return JSON.parse(dataString) as T
|
|
|
|
|
}
|
|
|
|
|
catch {
|
|
|
|
|
// avoid parse error
|
|
|
|
|
return null
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|