Add passphrase encryption module
PBKDF2-SHA256 -> AES-256-GCM via WebCrypto, with versioned blob header authenticated as GCM additional data. Tests cover round trip, wrong passphrase, tampering and malformed input. build.js bundles crypto.js into the single-file output. Closes #2 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
43
test/crypto.test.js
Normal file
43
test/crypto.test.js
Normal file
@@ -0,0 +1,43 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { encrypt, decrypt, DecryptError } from '../src/crypto.js';
|
||||
|
||||
const FAST = 1000; // iterations; production default is 600000
|
||||
const text = JSON.stringify({ note: 'ünïcødé ✓ secret 7419', big: 'x'.repeat(200000) });
|
||||
|
||||
test('round trip', async () => {
|
||||
const blob = await encrypt(text, 'correct horse', FAST);
|
||||
assert.equal(await decrypt(blob, 'correct horse'), text);
|
||||
});
|
||||
|
||||
test('same input encrypts differently each time (random salt/iv)', async () => {
|
||||
assert.notEqual(await encrypt('a', 'p', FAST), await encrypt('a', 'p', FAST));
|
||||
});
|
||||
|
||||
test('wrong passphrase fails cleanly', async () => {
|
||||
const blob = await encrypt(text, 'right', FAST);
|
||||
await assert.rejects(decrypt(blob, 'wrong'), DecryptError);
|
||||
await assert.rejects(decrypt(blob, ''), DecryptError);
|
||||
});
|
||||
|
||||
test('tampering with any region is detected', async () => {
|
||||
const blob = await encrypt('hello', 'p', FAST);
|
||||
const bytes = Uint8Array.from(atob(blob), (c) => c.charCodeAt(0));
|
||||
// header iterations, salt, iv, ciphertext, final tag byte
|
||||
for (const i of [4, 8, 20, 35, bytes.length - 1]) {
|
||||
const t = bytes.slice();
|
||||
t[i] ^= 1;
|
||||
await assert.rejects(decrypt(btoa(String.fromCharCode(...t)), 'p'), DecryptError, 'byte ' + i);
|
||||
}
|
||||
});
|
||||
|
||||
test('garbage and truncated input rejected', async () => {
|
||||
await assert.rejects(decrypt('not base64!!', 'p'), DecryptError);
|
||||
await assert.rejects(decrypt('', 'p'), DecryptError);
|
||||
const blob = await encrypt('hello', 'p', FAST);
|
||||
await assert.rejects(decrypt(blob.slice(0, 20), 'p'), DecryptError);
|
||||
});
|
||||
|
||||
test('empty passphrase refused on encrypt', async () => {
|
||||
await assert.rejects(encrypt('x', ''), /passphrase/);
|
||||
});
|
||||
Reference in New Issue
Block a user