-
Notifications
You must be signed in to change notification settings - Fork 0
/
encrypt.js
52 lines (46 loc) · 1.43 KB
/
encrypt.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
51
52
/**
* Encrypt a string.
* @param {string} plaintext - The string to encrypt.
* @param {string} password - The password used to encrypt the string.
* @returns {Promise<string>} A promise that resolves to the ciphertext.
*/
export async function encrypt(plaintext, password) {
const encoder = new TextEncoder();
const encodedPlaintext = encoder.encode(plaintext);
const encodedPassword = encoder.encode(password);
const additionalData = encoder.encode('https://github.com/ardislu/static-encrypt');
const salt = new Uint8Array(32);
const iv = new Uint8Array(12);
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, additionalData },
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;
}