76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import crypto from 'crypto';
|
|
|
|
const ALGORITHM = 'aes-256-cbc';
|
|
|
|
// 与前端对齐: SHA-256(KEY_STRING) → 32 bytes
|
|
const RAW_KEY = process.env.ENCRYPTION_KEY || 'maqt-delta-force-2024-secret-key-32';
|
|
const KEY = crypto.createHash('sha256').update(RAW_KEY).digest();
|
|
|
|
export interface EncryptedData {
|
|
encrypted: boolean;
|
|
iv: string;
|
|
data: string;
|
|
}
|
|
|
|
/**
|
|
* AES 加密
|
|
*/
|
|
export function encrypt(text: string): EncryptedData {
|
|
const iv = crypto.randomBytes(16);
|
|
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
|
|
let encrypted = cipher.update(text, 'utf-8', 'hex');
|
|
encrypted += cipher.final('hex');
|
|
|
|
return {
|
|
encrypted: true,
|
|
iv: iv.toString('hex'),
|
|
data: encrypted,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 加密整个 JSON 响应体(对齐前端 decryptData 格式)
|
|
*/
|
|
export function encryptResponse(payload: object): EncryptedData {
|
|
const json = JSON.stringify(payload);
|
|
const iv = crypto.randomBytes(16);
|
|
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
|
|
let encrypted = cipher.update(json, 'utf-8', 'hex');
|
|
encrypted += cipher.final('hex');
|
|
return { encrypted: true, iv: iv.toString('hex'), data: encrypted };
|
|
}
|
|
|
|
/**
|
|
* AES 解密
|
|
*/
|
|
export function decrypt(ivHex: string, dataHex: string): string {
|
|
const iv = Buffer.from(ivHex, 'hex');
|
|
const encryptedData = Buffer.from(dataHex, 'hex');
|
|
const decipher = crypto.createDecipheriv(ALGORITHM, KEY, iv);
|
|
let decrypted = decipher.update(encryptedData, undefined, 'utf-8');
|
|
decrypted += decipher.final('utf-8');
|
|
|
|
return decrypted;
|
|
}
|
|
|
|
/**
|
|
* 密码哈希
|
|
*/
|
|
export function hashPassword(password: string): string {
|
|
return crypto.createHash('sha256').update(password).digest('hex');
|
|
}
|
|
|
|
/**
|
|
* 生成随机字符串
|
|
*/
|
|
export function randomString(length: number = 32): string {
|
|
return crypto.randomBytes(length).toString('hex').slice(0, length);
|
|
}
|
|
|
|
/**
|
|
* 生成设备哈希
|
|
*/
|
|
export function generateDeviceHash(data: string): string {
|
|
return crypto.createHash('sha256').update(data).digest('hex').slice(0, 64);
|
|
}
|