From 56650d5842b102051c191ac14960616eba362b5a Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Wed, 22 Feb 2023 19:58:19 -0800 Subject: [PATCH] Move encrypt into its own module --- encrypt.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ index.html | 47 +---------------------------------------------- 2 files changed, 46 insertions(+), 46 deletions(-) create mode 100644 encrypt.js 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 @@