import { app } from 'electron' import path from 'path' import fs from 'fs' import crypto from 'crypto' import { createLogger } from '../utils/logger' const logger = createLogger('KeyService') const KEY_FILE = 'encryption.key' export class KeyService { private key: string | null = null // 获取或创建主密钥 getMasterKey(): string { if (this.key) return this.key const keyPath = path.join(app.getPath('userData'), KEY_FILE) // 尝试读取现有密钥 if (fs.existsSync(keyPath)) { try { this.key = fs.readFileSync(keyPath, 'utf8').trim() return this.key } catch (error) { logger.error('Failed to read master key:', error) } } // 生成新密钥 this.key = crypto.randomBytes(32).toString('hex') fs.writeFileSync(keyPath, this.key, { mode: 0o600 }) return this.key } // 清除密钥(登出时) clearKey(): void { this.key = null } } // 全局单例 export const keyService = new KeyService()