From: Ardis Lu Date: Tue, 21 Feb 2023 06:33:54 +0000 (-0800) Subject: Move decrypt into its own module X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=36c30206b7ebb3f1f7f96eca03b2df37f327058c;p=static-encrypt Move decrypt into its own module So there can be custom decryption frontends --- diff --git a/decrypt.js b/decrypt.js new file mode 100644 index 0000000..9132f5c --- /dev/null +++ b/decrypt.js @@ -0,0 +1,42 @@ +export default async function decrypt(content, password) { + const encodedPassword = new TextEncoder().encode(password); + + const contentBuffer = Uint8Array.from(atob(content), c => c.charCodeAt(0)); + const salt = new Uint8Array(32); + const iv = new Uint8Array(32); + const ciphertext = new Uint8Array(contentBuffer.byteLength - 64); + salt.set(contentBuffer.slice(0, 32)); + iv.set(contentBuffer.slice(32, 64)); + ciphertext.set(contentBuffer.slice(64)); + + const keyMaterial = await crypto.subtle.importKey( + 'raw', + encodedPassword, + 'PBKDF2', + false, + ['deriveKey'], + ); + + const key = await crypto.subtle.deriveKey( + { + name: 'PBKDF2', + hash: 'SHA-512', + salt, + iterations: 400_000, + }, + keyMaterial, + { name: 'AES-GCM', length: 256 }, + false, + ['decrypt'] + ); + + const encodedPlaintext = new Uint8Array(await crypto.subtle.decrypt( + { name: 'AES-GCM', iv }, + key, + ciphertext, + )); + + const plaintext = new TextDecoder().decode(encodedPlaintext); + + return plaintext; +} diff --git a/index.html b/index.html index d607f8e..8fe3874 100644 --- a/index.html +++ b/index.html @@ -126,6 +126,7 @@ return content; } + const { default: decrypt } = await import('/decrypt.js'); const template = await fetch('/template.html').then(r => r.text()); document.querySelector('form').addEventListener('submit', async e => { e.preventDefault(); @@ -135,7 +136,8 @@ const password = data.get('password'); const encrypted = await encrypt(content, password); - const output = template.replace("const content = 'DO_NOT_MODIFY_THIS_LINE';", `const content = '${encrypted}';`); + const scriptInjection = ` diff --git a/template.html b/template.html index fea5190..4ca08fa 100644 --- a/template.html +++ b/template.html @@ -24,60 +24,16 @@ +