57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import {beforeAll, expect, test} from 'bun:test'
|
|
|
|
import * as asymmetric from 'boxes/asymmetric'
|
|
|
|
let k1!: [asymmetric.PrivKey, asymmetric.PubKey];
|
|
let k2!: [asymmetric.PrivKey, asymmetric.PubKey];
|
|
|
|
beforeAll(async () => {
|
|
k1 = await asymmetric.PrivateBox.gen_keypair(false)
|
|
k2 = await asymmetric.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 asymmetric.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 asymmetric.PrivateBox.encrypt<Uint8Array>(pub, data)).expect("Should encrypt the data")
|
|
const str = box.toString()
|
|
const box2 = asymmetric.PrivateBox.fromString<Uint8Array>(str).expect("Should parse the string")
|
|
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 asymmetric.PrivateBox.encrypt<Uint8Array>(pub, data)).expect("Should encrypt the data")
|
|
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 asymmetric.PrivateBox.encrypt(pub, data)).expect("Should encrypt the data")
|
|
;(await box.decrypt(priv)).expect_err("Should fail to decrypt the data")
|
|
})
|