|
1
|
import crypto from "node:crypto" |
|
2
|
import Scrypt from "scrypt-kdf" |
|
3
|
|
|
4
|
const ENCRYPTION_VERSION = "v1" |
|
5
|
const RECOVERY_CODE_HASH_CONFIG = { logN: 15, r: 8, p: 1 } |
|
6
|
|
|
7
|
export function encryptSecret(secret: string, encryptionKey: string): string { |
|
8
|
const iv = crypto.randomBytes(12) |
|
9
|
const cipher = crypto.createCipheriv( |
|
10
|
"aes-256-gcm", |
|
11
|
deriveKey(encryptionKey), |
|
12
|
iv |
|
13
|
) |
|
14
|
const encrypted = Buffer.concat([ |
|
15
|
cipher.update(secret, "utf8"), |
|
16
|
cipher.final(), |
|
17
|
]) |
|
18
|
const tag = cipher.getAuthTag() |
|
19
|
|
|
20
|
return [ |
|
21
|
ENCRYPTION_VERSION, |
|
22
|
iv.toString("base64url"), |
|
23
|
tag.toString("base64url"), |
|
24
|
encrypted.toString("base64url"), |
|
25
|
].join(":") |
|
26
|
} |
|
27
|
|
|
28
|
export function decryptSecret(payload: string, encryptionKey: string): string { |
|
29
|
const [version, iv, tag, encrypted] = payload.split(":") |
|
30
|
|
|
31
|
if (version !== ENCRYPTION_VERSION || !iv || !tag || !encrypted) { |
|
32
|
throw new Error("Invalid encrypted MFA secret") |
|
33
|
} |
|
34
|
|
|
35
|
const decipher = crypto.createDecipheriv( |
|
36
|
"aes-256-gcm", |
|
37
|
deriveKey(encryptionKey), |
|
38
|
Buffer.from(iv, "base64url") |
|
39
|
) |
|
40
|
|
|
41
|
decipher.setAuthTag(Buffer.from(tag, "base64url")) |
|
42
|
|
|
43
|
return Buffer.concat([ |
|
44
|
decipher.update(Buffer.from(encrypted, "base64url")), |
|
45
|
decipher.final(), |
|
46
|
]).toString("utf8") |
|
47
|
} |
|
48
|
|
|
49
|
export function generateRecoveryCode(): string { |
|
50
|
return crypto |
|
51
|
.randomBytes(16) |
|
52
|
.toString("hex") |
|
53
|
.match(/.{1,4}/g)! |
|
54
|
.join("-") |
|
55
|
} |
|
56
|
|
|
57
|
export async function hashRecoveryCode(code: string): Promise<string> { |
|
58
|
const hash = await Scrypt.kdf( |
|
59
|
normalizeRecoveryCode(code), |
|
60
|
RECOVERY_CODE_HASH_CONFIG |
|
61
|
) |
|
62
|
|
|
63
|
return hash.toString("base64") |
|
64
|
} |
|
65
|
|
|
66
|
export async function verifyRecoveryCodeHash( |
|
67
|
hash: string, |
|
68
|
code: string |
|
69
|
): Promise<boolean> { |
|
70
|
return await Scrypt.verify( |
|
71
|
Buffer.from(hash, "base64"), |
|
72
|
normalizeRecoveryCode(code) |
|
73
|
) |
|
74
|
} |
|
75
|
|
|
76
|
function deriveKey(encryptionKey: string): Buffer { |
|
77
|
return crypto.createHash("sha256").update(encryptionKey).digest() |
|
78
|
} |
|
79
|
|
|
80
|
function normalizeRecoveryCode(code: string): string { |
|
81
|
return code.trim().toLowerCase() |
|
82
|
} |