flnxi-Wu/lib/license/crypto-service.ts
2026-05-26 16:04:30 +08:00

159 lines
4.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as crypto from 'crypto';
// RSA 公钥 - 必须通过环境变量配置,不再硬编码
const RSA_PUBLIC_KEY = (() => {
const key = process.env.LICENSE_PUBLIC_KEY?.replace(/\\n/g, '\n');
if (!key) {
console.error('[SECURITY] LICENSE_PUBLIC_KEY 环境变量未设置');
}
return key || '';
})();
// 本地加密密钥 - 必须通过环境变量配置,不再提供默认值
const LOCAL_ENCRYPTION_KEY = (() => {
const key = process.env.LOCAL_ENCRYPTION_KEY;
if (!key) {
console.error('[SECURITY] LOCAL_ENCRYPTION_KEY 环境变量未设置,本地加密功能将不可用');
}
// 密钥必须至少 32 字节
if (key && key.length < 32) {
console.error('[SECURITY] LOCAL_ENCRYPTION_KEY 长度不足 32 字节');
}
return key || '';
})();
// 检查安全配置
export function checkSecurityConfig(): { valid: boolean; errors: string[] } {
const errors: string[] = [];
if (!RSA_PUBLIC_KEY) {
errors.push('LICENSE_PUBLIC_KEY 未设置');
}
if (!LOCAL_ENCRYPTION_KEY) {
errors.push('LOCAL_ENCRYPTION_KEY 未设置');
} else if (LOCAL_ENCRYPTION_KEY.length < 32) {
errors.push('LOCAL_ENCRYPTION_KEY 长度不足 32 字节');
}
return {
valid: errors.length === 0,
errors
};
}
function getRequiredLocalEncryptionKey(): string {
if (!LOCAL_ENCRYPTION_KEY) {
throw new Error('LOCAL_ENCRYPTION_KEY 未设置,无法进行本地许可证加密');
}
if (LOCAL_ENCRYPTION_KEY.length < 32) {
throw new Error('LOCAL_ENCRYPTION_KEY 长度不足 32 字节,无法进行本地许可证加密');
}
return LOCAL_ENCRYPTION_KEY;
}
/**
* 使用 RSA 公钥验证签名
*/
export function verifySignature(data: string, signature: string): boolean {
try {
const verify = crypto.createVerify('RSA-SHA256');
verify.update(data);
verify.end();
return verify.verify(RSA_PUBLIC_KEY, signature, 'base64');
} catch (error) {
console.error('签名验证失败:', error);
return false;
}
}
/**
* 验证签名后的许可证数据
*/
export function verifyLicenseSignature(licenseData: object, signature: string): boolean {
const dataString = JSON.stringify(licenseData);
return verifySignature(dataString, signature);
}
/**
* 给本地运行状态生成 HMAC,防止低成本直接改数据库字段绕过授权限制。
*/
export function signLocalIntegrity(data: string): string {
return crypto
.createHmac('sha256', getRequiredLocalEncryptionKey())
.update(data)
.digest('hex');
}
export function verifyLocalIntegrity(data: string, signature: string): boolean {
try {
const expected = signLocalIntegrity(data);
const expectedBuffer = Buffer.from(expected, 'hex');
const signatureBuffer = Buffer.from(signature, 'hex');
return (
expectedBuffer.length === signatureBuffer.length &&
crypto.timingSafeEqual(expectedBuffer, signatureBuffer)
);
} catch {
return false;
}
}
/**
* 使用 AES-256-GCM 加密数据(用于本地存储)
*/
export function encryptLocal(plaintext: string): string {
const iv = crypto.randomBytes(12);
const key = crypto.scryptSync(getRequiredLocalEncryptionKey(), 'salt', 32);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'base64');
encrypted += cipher.final('base64');
const authTag = cipher.getAuthTag();
// 格式: iv:authTag:encrypted
return `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted}`;
}
/**
* 使用 AES-256-GCM 解密数据(用于本地存储)
*/
export function decryptLocal(ciphertext: string): string {
try {
const [ivBase64, authTagBase64, encrypted] = ciphertext.split(':');
const iv = Buffer.from(ivBase64, 'base64');
const authTag = Buffer.from(authTagBase64, 'base64');
const key = crypto.scryptSync(getRequiredLocalEncryptionKey(), 'salt', 32);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (error) {
console.error('解密失败:', error);
throw new Error('数据解密失败');
}
}
/**
* 计算数据哈希
*/
export function hashData(data: string): string {
return crypto.createHash('sha256').update(data).digest('hex');
}
/**
* 生成随机 ID
*/
export function generateId(): string {
return crypto.randomBytes(16).toString('hex');
}