-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecrypt.js
50 lines (44 loc) · 1.48 KB
/
decrypt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Decrypt an encrypted string.
* @param {string} content - The ciphertext to decrypt.
* @param {string} password - The password used to encrypt the string.
* @returns {Promise<string>} A promise that resolves to the plaintext.
*/
export async function decrypt(content, password) {
const encoder = new TextEncoder();
const encodedPassword = encoder.encode(password);
const additionalData = encoder.encode('https://github.com/ardislu/static-encrypt');
const contentBuffer = Uint8Array.from(atob(content), c => c.charCodeAt(0));
const salt = new Uint8Array(32);
const iv = new Uint8Array(12);
const ciphertext = new Uint8Array(contentBuffer.byteLength - salt.byteLength - iv.byteLength);
salt.set(contentBuffer.slice(0, salt.byteLength));
iv.set(contentBuffer.slice(salt.byteLength, salt.byteLength + iv.byteLength));
ciphertext.set(contentBuffer.slice(salt.byteLength + iv.byteLength));
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, additionalData },
key,
ciphertext
));
const plaintext = new TextDecoder().decode(encodedPlaintext);
return plaintext;
}