Files
libcrypto/test/boxes/symmetric.test.ts
T
2024-05-21 16:00:16 +02:00

58 lines
2.2 KiB
TypeScript

import {expect, test} from 'bun:test'
import * as symmetric from 'boxes/symmetric'
test('base case', async () => {
const key = await symmetric.SecretBox.gen_key()
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await symmetric.SecretBox.encrypt<Uint8Array>(key, data)).expect("Should encrypt the data")
const result = (await box.decrypt(key)).expect("Should decrypt the data")
expect(result).toEqual(data)
})
test('toString and fromString are inverses', async () => {
const key = await symmetric.SecretBox.gen_key()
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await symmetric.SecretBox.encrypt<Uint8Array>(key, data)).expect("Should encrypt the data")
const str = box.toString()
const box2 = symmetric.SecretBox.fromString<Uint8Array>(str).expect("Should parse the string")
expect(box).toEqual(box2)
const plain = (await box2.decrypt(key)).expect("Should decrypt the data")
expect(plain).toEqual(data)
})
test('tampered cipher fails', async () => {
const key = await symmetric.SecretBox.gen_key()
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await symmetric.SecretBox.encrypt<Uint8Array>(key, data)).expect("Should encrypt the data")
// @ts-expect-error : This is a test, so it's OK to access private field
box.cipher[0] += 1
;(await box.decrypt(key)).expect_err("Should fail to decrypt the data")
})
test('Wrong key fails', async () => {
const key1 = await symmetric.SecretBox.gen_key()
const key2 = await symmetric.SecretBox.gen_key()
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await symmetric.SecretBox.encrypt(key1, data)).expect("Should encrypt the data")
;(await box.decrypt(key2)).expect_err("Should fail to decrypt the data")
})
test('tampered IV fails', async () => {
const key = await symmetric.SecretBox.gen_key()
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await symmetric.SecretBox.encrypt<Uint8Array>(key, data)).expect("Should encrypt the data")
// @ts-expect-error : This is a test, so it's OK to access private field
box.iv[0] += 1
;(await box.decrypt(key)).expect_err("Should fail to decrypt the data")
})