From 66ca565bad6be6d9ecfe5f14578833a507f45f33 Mon Sep 17 00:00:00 2001 From: Ry Racherbaumer Date: Fri, 19 Jan 2024 16:29:17 -0600 Subject: [PATCH] test: add HMAC encryption tests --- test/crypto/encryption.test.ts | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 test/crypto/encryption.test.ts diff --git a/test/crypto/encryption.test.ts b/test/crypto/encryption.test.ts new file mode 100644 index 000000000..4e95f925f --- /dev/null +++ b/test/crypto/encryption.test.ts @@ -0,0 +1,62 @@ +import { + importHmacKey, + exportHmacKey, + hkdfHmacKey, + validateHmac, + generateHmac, +} from '../../src/crypto/encryption' +import crypto from '../../src/crypto/crypto' + +describe('HMAC encryption', () => { + it('generates and validates HMAC', async () => { + const secret = crypto.getRandomValues(new Uint8Array(32)) + const salt = crypto.getRandomValues(new Uint8Array(32)) + const message = crypto.getRandomValues(new Uint8Array(32)) + const hmac = await generateHmac(secret, salt, message) + const key = await hkdfHmacKey(secret, salt) + const valid = await validateHmac(key, hmac, message) + expect(valid).toBe(true) + }) + + it('generates and validates HMAC with imported key', async () => { + const secret = crypto.getRandomValues(new Uint8Array(32)) + const salt = crypto.getRandomValues(new Uint8Array(32)) + const message = crypto.getRandomValues(new Uint8Array(32)) + const hmac = await generateHmac(secret, salt, message) + const key = await hkdfHmacKey(secret, salt) + const exportedKey = await exportHmacKey(key) + const importedKey = await importHmacKey(exportedKey) + const valid = await validateHmac(importedKey, hmac, message) + expect(valid).toBe(true) + }) + + it('fails to validate HMAC with wrong message', async () => { + const secret = crypto.getRandomValues(new Uint8Array(32)) + const salt = crypto.getRandomValues(new Uint8Array(32)) + const message = crypto.getRandomValues(new Uint8Array(32)) + const hmac = await generateHmac(secret, salt, message) + const key = await hkdfHmacKey(secret, salt) + const valid = await validateHmac( + key, + hmac, + crypto.getRandomValues(new Uint8Array(32)) + ) + expect(valid).toBe(false) + }) + + it('fails to validate HMAC with wrong key', async () => { + const secret = crypto.getRandomValues(new Uint8Array(32)) + const salt = crypto.getRandomValues(new Uint8Array(32)) + const message = crypto.getRandomValues(new Uint8Array(32)) + const hmac = await generateHmac(secret, salt, message) + const valid = await validateHmac( + await hkdfHmacKey( + crypto.getRandomValues(new Uint8Array(32)), + crypto.getRandomValues(new Uint8Array(32)) + ), + hmac, + message + ) + expect(valid).toBe(false) + }) +})