This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
90 lines (75 loc) · 1.83 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class NextCrypto {
constructor(secret) {
this.secret = secret;
}
async encrypt(plain) {
if (!crypto) {
throw new Error(
'No WebAPI crypto module found. Do you call me in the right place?',
);
}
const iv = crypto.getRandomValues(new Uint8Array(12));
const alg = { name: 'AES-GCM', iv };
const keyHash = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(this.secret),
);
const encodedPlaintext = new TextEncoder().encode(plain);
const secretKey = await crypto.subtle.importKey(
'raw',
keyHash,
alg,
false,
['encrypt'],
);
const ciphertext = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv,
},
secretKey,
encodedPlaintext,
);
return `${Buffer.from(ciphertext).toString('base64')};${Buffer.from(
iv,
).toString('base64')}`;
}
async decrypt(encrypted) {
if (!crypto) {
throw new Error(
'No WebAPI crypto module found. Do you call me in the right place?',
);
}
const ciphertext = encrypted.split(';')[0];
const iv = encrypted.split(';')[1];
if (!ciphertext || !iv) {
return null;
}
const alg = { name: 'AES-GCM', iv };
const keyHash = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(this.secret),
);
const secretKey = await crypto.subtle.importKey(
'raw',
keyHash,
alg,
false,
['decrypt'],
);
try {
const cleartext = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: Buffer.from(iv, 'base64'),
},
secretKey,
Buffer.from(ciphertext, 'base64'),
);
return new TextDecoder().decode(cleartext);
} catch (e) {
return null;
}
}
}
module.exports = NextCrypto;