|
|
import CryptoJS from 'crypto-js';
|
|
|
|
|
|
// 加密密钥 - 建议从环境变量读取,这里使用固定密钥作为示例
|
|
|
const SECRET_KEY = 'flow-platform-2025-secret-key';
|
|
|
|
|
|
/**
|
|
|
* AES 加密
|
|
|
* @param data 需要加密的数据(对象会被序列化为 JSON)
|
|
|
* @returns 加密后的字符串
|
|
|
*/
|
|
|
export function encrypt(data: any): string {
|
|
|
try {
|
|
|
const jsonString = typeof data === 'string' ? data : JSON.stringify(data);
|
|
|
const encrypted = CryptoJS.AES.encrypt(jsonString, SECRET_KEY).toString();
|
|
|
return encrypted;
|
|
|
} catch (error) {
|
|
|
console.error('加密失败:', error);
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* AES 解密
|
|
|
* @param encryptedData 加密的字符串
|
|
|
* @returns 解密后的数据(如果是 JSON 对象会自动解析)
|
|
|
*/
|
|
|
export function decrypt(encryptedData: string): any {
|
|
|
try {
|
|
|
const bytes = CryptoJS.AES.decrypt(encryptedData, SECRET_KEY);
|
|
|
const decryptedString = bytes.toString(CryptoJS.enc.Utf8);
|
|
|
|
|
|
if (!decryptedString) {
|
|
|
throw new Error('解密失败:无法解析数据');
|
|
|
}
|
|
|
|
|
|
// 尝试解析为 JSON,如果失败则返回原始字符串
|
|
|
try {
|
|
|
return JSON.parse(decryptedString);
|
|
|
} catch {
|
|
|
return decryptedString;
|
|
|
}
|
|
|
} catch (error) {
|
|
|
console.error('解密失败:', error);
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 加密登录参数(用户名和密码)
|
|
|
* @param params 包含 username 和 password 的对象
|
|
|
* @returns 加密后的字符串
|
|
|
*/
|
|
|
export function encryptLoginParams(params: { username: string; password: string }): string {
|
|
|
return encrypt(params);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 解密登录参数
|
|
|
* @param encryptedParams 加密的登录参数字符串
|
|
|
* @returns 解密后的对象,包含 username 和 password
|
|
|
*/
|
|
|
export function decryptLoginParams(encryptedParams: string): { username: string; password: string } | null {
|
|
|
try {
|
|
|
return decrypt(encryptedParams);
|
|
|
} catch (error) {
|
|
|
console.error('解密登录参数失败:', error);
|
|
|
return null;
|
|
|
}
|
|
|
}
|