Initial
This commit is contained in:
13
frontend/js-encryption/decrypt.js
Normal file
13
frontend/js-encryption/decrypt.js
Normal file
@@ -0,0 +1,13 @@
|
||||
async function decrypt(ciphertext, password) {
|
||||
const pwUtf8 = new TextEncoder().encode(password);
|
||||
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
|
||||
const ctUtf8 = new Uint8Array(Array.from(atob(ciphertext)).map(x => x.charCodeAt(0)));
|
||||
const alg = { name: 'AES-GCM', iv: ctUtf8.slice(0,12) };
|
||||
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']);
|
||||
try {
|
||||
const buf = await crypto.subtle.decrypt(alg, key, ctUtf8.slice(12));
|
||||
return new TextDecoder().decode(buf);
|
||||
} catch (e) {
|
||||
throw new Error('Decrypt failed')
|
||||
}
|
||||
}
|
||||
11
frontend/js-encryption/encrypt.js
Normal file
11
frontend/js-encryption/encrypt.js
Normal file
@@ -0,0 +1,11 @@
|
||||
async function encrypt(plaintext, password) {
|
||||
const pwUtf8 = new TextEncoder().encode(password);
|
||||
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const alg = { name: 'AES-GCM', iv: iv };
|
||||
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
|
||||
const ptUint8 = new TextEncoder().encode(plaintext);
|
||||
const buf = await crypto.subtle.encrypt(alg, key, ptUint8);
|
||||
const ctStr = Array.from(new Uint8Array(buf)).map(b => String.fromCharCode(b)).join('');
|
||||
return btoa(String.fromCharCode(...iv) + ctStr);
|
||||
}
|
||||
Reference in New Issue
Block a user