Repository navigation
Expand file tree
/
Copy pathcrypto.ts
More file actions
178 lines (149 loc) · 5.36 KB
/
Copy pathcrypto.ts
File metadata and controls
178 lines (149 loc) · 5.36 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/**
* Cryptography utilities for end-to-end encryption
*
* This module provides functions for:
* 1. Generating encryption keys from user passwords
* 2. Encrypting and decrypting sensitive data
* 3. Securely storing encryption keys
*/
import { pbkdf2, randomBytes, createCipheriv, createDecipheriv } from 'crypto';
import { promisify } from 'util';
const pbkdf2Async = promisify(pbkdf2);
// Constants for encryption
const ALGORITHM = 'aes-256-gcm';
const KEY_LENGTH = 32; // 256 bits
const IV_LENGTH = 12; // 12 bytes per NIST SP 800-38D recommendation for AES-GCM
const SALT_LENGTH = 16;
const AUTH_TAG_LENGTH = 16;
const ITERATIONS = 100000;
/**
* Derives an encryption key from a user's master password
*/
export async function deriveKeyFromPassword(password: string, salt?: Buffer): Promise<{ key: Buffer; salt: Buffer }> {
const saltBuffer = salt || randomBytes(SALT_LENGTH);
const key = await pbkdf2Async(password, saltBuffer, ITERATIONS, KEY_LENGTH, 'sha256');
return { key, salt: saltBuffer };
}
/**
* Encrypts data using the provided key
*/
export function encrypt(data: string, key: Buffer): { encrypted: string; iv: Buffer; authTag: Buffer } {
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv);
let encrypted = cipher.update(data, 'utf8', 'base64');
encrypted += cipher.final('base64');
const authTag = cipher.getAuthTag();
return {
encrypted,
iv,
authTag
};
}
/**
* Decrypts data using the provided key
*/
export function decrypt(encryptedData: string, key: Buffer, iv: Buffer, authTag: Buffer): string {
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encryptedData, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
/**
* Formats encrypted data for storage
*/
export function formatEncryptedData(encrypted: string, iv: Buffer, authTag: Buffer, salt: Buffer): string {
const ivHex = iv.toString('hex');
const authTagHex = authTag.toString('hex');
const saltHex = salt.toString('hex');
return `${encrypted}:${ivHex}:${authTagHex}:${saltHex}`;
}
/**
* Parses encrypted data from storage format
*/
export function parseEncryptedData(data: string): {
encrypted: string;
iv: Buffer;
authTag: Buffer;
salt: Buffer;
} {
const [encrypted, ivHex, authTagHex, saltHex] = data.split(':');
return {
encrypted,
iv: Buffer.from(ivHex, 'hex'),
authTag: Buffer.from(authTagHex, 'hex'),
salt: Buffer.from(saltHex, 'hex')
};
}
/**
* Encrypts an object with sensitive data
*/
export async function encryptObject<T extends Record<string, any>>(
obj: T,
key: Buffer,
fieldsToEncrypt: (keyof T)[]
): Promise<{ encryptedObj: T; encryptionData: Record<string, { iv: string; authTag: string; salt: string }> }> {
const encryptedObj = { ...obj };
const encryptionData: Record<string, { iv: string; authTag: string; salt: string }> = {};
for (const field of fieldsToEncrypt) {
if (typeof obj[field] === 'string') {
const salt = randomBytes(SALT_LENGTH);
const { key: derivedKey } = await deriveKeyFromPassword(key.toString('hex'), salt);
const { encrypted, iv, authTag } = encrypt(obj[field] as string, derivedKey);
encryptedObj[field] = encrypted as any;
encryptionData[field as string] = {
iv: iv.toString('hex'),
authTag: authTag.toString('hex'),
salt: salt.toString('hex')
};
}
}
return { encryptedObj, encryptionData };
}
/**
* Decrypts an object with encrypted data
*/
export async function decryptObject<T extends Record<string, any>>(
obj: T,
key: Buffer,
fieldsToDecrypt: (keyof T)[],
encryptionData: Record<string, { iv: string; authTag: string; salt: string }>
): Promise<T> {
const decryptedObj = { ...obj };
for (const field of fieldsToDecrypt) {
if (typeof obj[field] === 'string' && encryptionData[field as string]) {
const { iv, authTag, salt } = encryptionData[field as string];
const ivBuffer = Buffer.from(iv, 'hex');
const authTagBuffer = Buffer.from(authTag, 'hex');
const saltBuffer = Buffer.from(salt, 'hex');
const { key: derivedKey } = await deriveKeyFromPassword(key.toString('hex'), saltBuffer);
const decrypted = decrypt(obj[field] as string, derivedKey, ivBuffer, authTagBuffer);
decryptedObj[field] = decrypted as any;
}
}
return decryptedObj;
}
/**
* Generates a secure encryption key for the user
*/
export function generateEncryptionKey(): Buffer {
return randomBytes(KEY_LENGTH);
}
/**
* Encrypts the user's encryption key with their master password
* for secure storage
*/
export async function encryptEncryptionKey(encryptionKey: Buffer, masterPassword: string): Promise<string> {
const { key, salt } = await deriveKeyFromPassword(masterPassword);
const { encrypted, iv, authTag } = encrypt(encryptionKey.toString('hex'), key);
return formatEncryptedData(encrypted, iv, authTag, salt);
}
/**
* Decrypts the user's encryption key using their master password
*/
export async function decryptEncryptionKey(encryptedKey: string, masterPassword: string): Promise<Buffer> {
const { encrypted, iv, authTag, salt } = parseEncryptedData(encryptedKey);
const { key } = await deriveKeyFromPassword(masterPassword, salt);
const decryptedKeyHex = decrypt(encrypted, key, iv, authTag);
return Buffer.from(decryptedKeyHex, 'hex');
}