69 lines
2.1 KiB
TypeScript
69 lines
2.1 KiB
TypeScript
import {beforeAll, expect, test} from 'bun:test'
|
|
import {misc, PrivateBox} from '..'
|
|
import {pubkey_toString} from '../src/misc'
|
|
|
|
let k1!: CryptoKeyPair
|
|
let k2!: CryptoKeyPair
|
|
let message!: Uint8Array
|
|
|
|
beforeAll(async () => {
|
|
k1 = await PrivateBox.gen(false)
|
|
k2 = await PrivateBox.gen(true)
|
|
message = misc.payload_fromString('Salut ! ça va ?')
|
|
})
|
|
|
|
test('base case', async () => {
|
|
const box = await PrivateBox.encrypt(message, k1.publicKey)
|
|
expect(box).not.toBeNull()
|
|
const unboxed = await box!.decrypt(k1.privateKey)
|
|
expect(unboxed).toEqual(message)
|
|
})
|
|
test("Different key can't decrypt", async () => {
|
|
const box = await PrivateBox.encrypt(message, k1.publicKey)
|
|
expect(box).not.toBeNull()
|
|
const unboxed = await box!.decrypt(k2.privateKey)
|
|
expect(unboxed).toBeNull()
|
|
})
|
|
|
|
test('Key generation', async () => {
|
|
const ser1 = await pubkey_toString(k1.publicKey)
|
|
const ser2 = await pubkey_toString(k2.publicKey)
|
|
expect(ser1).not.toEqual(ser2)
|
|
|
|
expect(k1.privateKey.extractable).toBeFalse()
|
|
expect(k1.publicKey.extractable).toBeTrue()
|
|
expect(k2.privateKey.extractable).toBeTrue()
|
|
expect(k2.publicKey.extractable).toBeTrue()
|
|
})
|
|
|
|
test('Encrypt with context', async () => {
|
|
const context = 'Super context !'
|
|
const box = await PrivateBox.encrypt(message, k1.publicKey, context)
|
|
expect(box).not.toBeNull()
|
|
const unboxed = await box!.decrypt(k1.privateKey, context)
|
|
expect(unboxed).toEqual(message)
|
|
})
|
|
test('Encrypt with different context', async () => {
|
|
const context1 = 'Super context !'
|
|
const context2 = 'Awesome context !'
|
|
const box = await PrivateBox.encrypt(message, k1.publicKey, context1)
|
|
expect(box).not.toBeNull()
|
|
const unboxed = await box!.decrypt(k1.privateKey, context2)
|
|
expect(unboxed).toBeNull()
|
|
})
|
|
|
|
test('serialization', async () => {
|
|
const box = await PrivateBox.encrypt(message, k1.publicKey)
|
|
expect(box).not.toBeNull()
|
|
|
|
const ser = await box!.toString()
|
|
const de = await PrivateBox.fromString(ser)
|
|
|
|
expect(de).not.toBeNull()
|
|
expect(de).toEqual(box)
|
|
|
|
const unboxed = await de!.decrypt(k1.privateKey)
|
|
expect(unboxed).not.toBeNull()
|
|
expect(unboxed).toEqual(message)
|
|
})
|