-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.ts
More file actions
80 lines (69 loc) · 1.92 KB
/
Copy pathcrypto.ts
File metadata and controls
80 lines (69 loc) · 1.92 KB
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
const APP_SALT = "tryskills.sh-v1";
const ITERATIONS = 100_000;
// Helpers return Uint8Array<ArrayBuffer> (not SharedArrayBuffer-backed) so they
// satisfy WebCrypto BufferSource in both Node and jsdom realms.
function textToBytes(text: string): Uint8Array<ArrayBuffer> {
return new Uint8Array(new TextEncoder().encode(text));
}
function bytesToHex(bytes: Uint8Array | ArrayBuffer): string {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
return Array.from(view)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
function hexToBytes(hex: string): Uint8Array<ArrayBuffer> {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
}
return bytes;
}
export async function deriveKey(userId: string): Promise<CryptoKey> {
const keyMaterial = await crypto.subtle.importKey(
"raw",
textToBytes(userId),
"PBKDF2",
false,
["deriveKey"],
);
return crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: textToBytes(APP_SALT),
iterations: ITERATIONS,
hash: "SHA-256",
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
export async function encrypt(
plaintext: string,
key: CryptoKey,
): Promise<{ ciphertext: string; iv: string }> {
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoded = textToBytes(plaintext);
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
encoded,
);
return {
ciphertext: bytesToHex(encrypted),
iv: bytesToHex(iv),
};
}
export async function decrypt(
ciphertext: string,
iv: string,
key: CryptoKey,
): Promise<string> {
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: hexToBytes(iv) },
key,
hexToBytes(ciphertext),
);
return new TextDecoder().decode(decrypted);
}