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:
94
src/crypto.js
Normal file
94
src/crypto.js
Normal file
@@ -0,0 +1,94 @@
|
||||
// Passphrase encryption: PBKDF2-SHA256 -> AES-256-GCM, WebCrypto only.
|
||||
// Runs unchanged in browsers and Node 20+. build.js strips the `export`
|
||||
// keywords when inlining this into the single-file bundle.
|
||||
//
|
||||
// Blob layout (base64 of): "FW" 0x01 | iterations u32be | salt 16 | iv 12 | ciphertext+tag
|
||||
// The 7-byte header + salt + iv are bound in as GCM additional data, so any
|
||||
// tampering with them fails authentication just like tampering with the ciphertext.
|
||||
|
||||
const MAGIC = [0x46, 0x57, 0x01]; // "FW" version 1
|
||||
const SALT_LEN = 16;
|
||||
const IV_LEN = 12;
|
||||
const HEADER_LEN = MAGIC.length + 4;
|
||||
const DEFAULT_ITERATIONS = 600000; // OWASP 2023 guidance for PBKDF2-SHA256
|
||||
const MAX_ITERATIONS = 10000000; // refuse absurd values from a hostile blob
|
||||
|
||||
export class DecryptError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'DecryptError';
|
||||
}
|
||||
}
|
||||
|
||||
function toBase64(bytes) {
|
||||
let s = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) {
|
||||
s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
}
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
function fromBase64(str) {
|
||||
try {
|
||||
const s = atob(str.trim());
|
||||
const out = new Uint8Array(s.length);
|
||||
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
||||
return out;
|
||||
} catch {
|
||||
throw new DecryptError('Not a valid encrypted file.');
|
||||
}
|
||||
}
|
||||
|
||||
async function deriveKey(passphrase, salt, iterations) {
|
||||
const base = await crypto.subtle.importKey(
|
||||
'raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey']);
|
||||
return crypto.subtle.deriveKey(
|
||||
{ name: 'PBKDF2', hash: 'SHA-256', salt, iterations },
|
||||
base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
|
||||
// Returns a base64 string. `iterations` is overridable for fast tests only.
|
||||
export async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERATIONS) {
|
||||
if (!passphrase) throw new Error('A passphrase is required.');
|
||||
const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
|
||||
const iv = crypto.getRandomValues(new Uint8Array(IV_LEN));
|
||||
const head = new Uint8Array(HEADER_LEN + SALT_LEN + IV_LEN);
|
||||
head.set(MAGIC, 0);
|
||||
new DataView(head.buffer).setUint32(MAGIC.length, iterations);
|
||||
head.set(salt, HEADER_LEN);
|
||||
head.set(iv, HEADER_LEN + SALT_LEN);
|
||||
|
||||
const key = await deriveKey(passphrase, salt, iterations);
|
||||
const ct = new Uint8Array(await crypto.subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv, additionalData: head }, key, new TextEncoder().encode(plaintext)));
|
||||
|
||||
const out = new Uint8Array(head.length + ct.length);
|
||||
out.set(head, 0);
|
||||
out.set(ct, head.length);
|
||||
return toBase64(out);
|
||||
}
|
||||
|
||||
// Throws DecryptError for a wrong passphrase, corruption, or tampering
|
||||
// (these are deliberately indistinguishable).
|
||||
export async function decrypt(blob, passphrase) {
|
||||
const bytes = fromBase64(blob);
|
||||
const preamble = HEADER_LEN + SALT_LEN + IV_LEN;
|
||||
if (bytes.length < preamble + 16 || MAGIC.some((b, i) => bytes[i] !== b)) {
|
||||
throw new DecryptError('Not a valid encrypted file.');
|
||||
}
|
||||
const iterations = new DataView(bytes.buffer, bytes.byteOffset).getUint32(MAGIC.length);
|
||||
if (iterations < 1 || iterations > MAX_ITERATIONS) {
|
||||
throw new DecryptError('Not a valid encrypted file.');
|
||||
}
|
||||
const head = bytes.slice(0, preamble);
|
||||
const salt = bytes.slice(HEADER_LEN, HEADER_LEN + SALT_LEN);
|
||||
const iv = bytes.slice(HEADER_LEN + SALT_LEN, preamble);
|
||||
try {
|
||||
const key = await deriveKey(passphrase || '', salt, iterations);
|
||||
const pt = await crypto.subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv, additionalData: head }, key, bytes.slice(preamble));
|
||||
return new TextDecoder().decode(pt);
|
||||
} catch {
|
||||
throw new DecryptError('Wrong passphrase, or the file is damaged.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user