import { beforeAll, describe, expect, it } from 'vitest' import { fromBase64, toBase64 } from '../data/bin' import { decryptAesGcm, encryptAesGcm } from './aes-sealed' import { deriveKeyPbkdf2 } from './crypto' describe('aes Encryption and Decryption', () => { let key: CryptoKey beforeAll(async () => { key = await crypto.subtle.generateKey( { name: 'AES-GCM', length: 256, }, true, ['encrypt', 'decrypt'], ) }) it('should encrypt and decrypt data correctly', async () => { const data = new TextEncoder().encode('Hello, World!') const encryptedData = await encryptAesGcm(data, key) const decryptedData = await decryptAesGcm(encryptedData, key) expect(new TextDecoder().decode(decryptedData)).toBe('Hello, World!') }) it('should produce different ciphertexts for the same plaintext', async () => { const data = new TextEncoder().encode('Hello, World!') const encryptedData1 = await encryptAesGcm(data, key) const encryptedData2 = await encryptAesGcm(data, key) expect(encryptedData1).not.toEqual(encryptedData2) }) it('should fail to decrypt with a different key', async () => { const data = new TextEncoder().encode('Hello, World!') const encryptedData = await encryptAesGcm(data, key) const differentKey = await crypto.subtle.generateKey( { name: 'AES-GCM', length: 256, }, true, ['encrypt', 'decrypt'], ) await expect(decryptAesGcm(encryptedData, differentKey)).rejects.toThrow() }) it('should decrypt a sample that was generated by Swift code', async () => { const key = await deriveKeyPbkdf2(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), { salt: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), iterations: 100000, }) const dataFromKey = await crypto.subtle.exportKey('raw', key) expect(toBase64(dataFromKey)).toMatchInlineSnapshot(`"UDl7buu/Zn/UxCIEp55MOTOKcDHvb959P+eyozok7BA="`) // Create for Swift sample // const sample = new Uint8Array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) // const encryptedData2 = await hxEncrypt(sample, key) // expect(toBase64(encryptedData2)).toMatchInlineSnapshot(`"Akjv9nbmkMUsbYg3TuJIXjafK9kUkZMdJ49XdapndkFtiuLVEyg="`) // From Swift sample const encryptedData = fromBase64('pVzIX88DZNjLw1VLLEnsIaqt4/jq4ZGJc8qDU2YruZJr6N9V0i0=') const decryptedData = await decryptAesGcm(encryptedData, key) expect(decryptedData).toMatchInlineSnapshot(` Uint8Array [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ] `) }) })