Implement boxes

This commit is contained in:
2024-05-21 16:00:16 +02:00
parent e515c80f36
commit d845ae1391
15 changed files with 920 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
import {beforeAll, expect, test} from 'bun:test'
import {type KeyPair, PrivateBox} from 'boxes/asymmetric'
let k1!: KeyPair;
let k2!: KeyPair;
beforeAll(async () => {
k1 = await PrivateBox.gen_keypair(false)
k2 = await PrivateBox.gen_keypair(true)
expect(k1[0].extractable).toBe(false)
expect(k1[1].extractable).toBe(true)
expect(k2[0].extractable).toBe(true)
expect(k2[1].extractable).toBe(true)
})
test('base case', async () => {
const [priv, pub] = k1
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await PrivateBox.encrypt<Uint8Array>(pub, data)).expect("Should encrypt the data")
const result = (await box.decrypt(priv)).expect("Should decrypt the data")
expect(result).toEqual(data)
})
test('toString and fromString are inverses', async () => {
const [priv, pub] = k1
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await PrivateBox.encrypt<Uint8Array>(pub, data)).expect("Should encrypt the data")
const str = box.toString()
const box2 = PrivateBox.fromString<Uint8Array>(str).expect("Should parse the string")
expect(box).toEqual(box2)
const plain = (await box2.decrypt(priv)).expect("Should decrypt the data")
expect(plain).toEqual(data)
})
test('Tampered cipher fails', async () => {
const [priv, pub] = k1
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await PrivateBox.encrypt<Uint8Array>(pub, data)).expect("Should encrypt the data")
// @ts-expect-error : Bypass privacy for test
box.cipher[0] += 1
;(await box.decrypt(priv)).expect_err("Should fail to decrypt the data")
})
test('Wrong pubkey should fail', async () => {
const [_priv, pub] = k1
const [priv, _pub] = k2
const data = new Uint8Array([1, 2, 3, 4, 5])
const box = (await PrivateBox.encrypt(pub, data)).expect("Should encrypt the data")
;(await box.decrypt(priv)).expect_err("Should fail to decrypt the data")
})