From: Ardis Lu Date: Thu, 23 Feb 2023 03:58:19 +0000 (-0800) Subject: Move encrypt into its own module X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=56650d5842b102051c191ac14960616eba362b5a;p=static-encrypt Move encrypt into its own module --- diff --git a/encrypt.js b/encrypt.js new file mode 100644 index 0000000..febaffa --- /dev/null +++ b/encrypt.js @@ -0,0 +1,45 @@ +export default async function encrypt(plaintext, password) { + const encoder = new TextEncoder(); + const encodedPlaintext = encoder.encode(plaintext); + const encodedPassword = encoder.encode(password); + + const salt = new Uint8Array(32); + const iv = new Uint8Array(32); + crypto.getRandomValues(salt); + crypto.getRandomValues(iv); + + 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, + ['encrypt'] + ); + + const ciphertext = new Uint8Array(await crypto.subtle.encrypt( + { name: 'AES-GCM', iv }, + key, + encodedPlaintext + )); + + const contentBuffer = new Uint8Array(salt.byteLength + iv.byteLength + ciphertext.byteLength); + contentBuffer.set(salt); + contentBuffer.set(iv, salt.byteLength); + contentBuffer.set(ciphertext, salt.byteLength + iv.byteLength); + const content = btoa(String.fromCharCode(...contentBuffer)); + + return content; +} \ No newline at end of file diff --git a/index.html b/index.html index 35caf7c..0a7f3c4 100644 --- a/index.html +++ b/index.html @@ -136,54 +136,9 @@