/** * Crypto Service Integration Tests * 验证加密/解密核心逻辑的正确性和安全性 */ import { describe, it, expect } from 'vitest' import { encrypt, decrypt, encryptAsync, simpleEncrypt, simpleDecrypt } from '../../electron/services/crypto' describe('Crypto Service', () => { const testPassword = 'test-password-123' const testData = 'Hello, OpsXShell! 你好,世界!' const testKey = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' describe('encrypt / decrypt', () => { it('应该能正确加密和解密数据', () => { const encrypted = encrypt(testData, testPassword) expect(encrypted).toBeTruthy() expect(encrypted).toContain(':') // 格式: version:salt:iv:tag:ciphertext const decrypted = decrypt(encrypted, testPassword) expect(decrypted).toBe(testData) }) it('密文应该包含版本标识', () => { const encrypted = encrypt(testData, testPassword) const parts = encrypted.split(':') expect(parts.length).toBe(5) expect(parts[0]).toBe('v1') }) it('不同密码应该产生不同密文', () => { const encrypted1 = encrypt(testData, testPassword) const encrypted2 = encrypt(testData, 'different-password') expect(encrypted1).not.toBe(encrypted2) }) it('相同数据多次加密应该产生不同密文(随机 salt/iv)', () => { const encrypted1 = encrypt(testData, testPassword) const encrypted2 = encrypt(testData, testPassword) expect(encrypted1).not.toBe(encrypted2) // 但都能正确解密 expect(decrypt(encrypted1, testPassword)).toBe(testData) expect(decrypt(encrypted2, testPassword)).toBe(testData) }) it('错误密码应该抛出异常', () => { const encrypted = encrypt(testData, testPassword) expect(() => decrypt(encrypted, 'wrong-password')).toThrow('Decryption failed') }) it('应该向后兼容旧格式密文(4部分,无版本标识)', () => { // 构造一个旧格式密文: salt:iv:tag:ciphertext const encrypted = encrypt(testData, testPassword) const parts = encrypted.split(':') const oldFormat = parts.slice(1).join(':') // 去掉版本标识 expect(decrypt(oldFormat, testPassword)).toBe(testData) }) }) describe('encryptAsync / decrypt', () => { it('异步加密应该产生可解密的结果', async () => { const encrypted = await encryptAsync(testData, testPassword) const decrypted = decrypt(encrypted, testPassword) expect(decrypted).toBe(testData) }) it('异步加密密文应该包含版本标识', async () => { const encrypted = await encryptAsync(testData, testPassword) const parts = encrypted.split(':') expect(parts.length).toBe(5) expect(parts[0]).toBe('v1') }) }) describe('simpleEncrypt / simpleDecrypt', () => { it('应该能正确加密和解密数据', () => { const encrypted = simpleEncrypt(testData, testKey) expect(encrypted).toBeTruthy() const decrypted = simpleDecrypt(encrypted, testKey) expect(decrypted).toBe(testData) }) it('错误密钥应该抛出异常', () => { const encrypted = simpleEncrypt(testData, testKey) expect(() => simpleDecrypt(encrypted, 'wrong-key')).toThrow('Decryption failed') }) it('无效密钥长度应该抛出异常', () => { expect(() => simpleEncrypt(testData, 'short')).toThrow('Invalid key length') }) }) })