-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptoManager.ts
More file actions
569 lines (496 loc) · 14.8 KB
/
Copy pathcryptoManager.ts
File metadata and controls
569 lines (496 loc) · 14.8 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/**
* WebCrypto End-to-End Encryption Manager
* Provides client-side encryption using Web Crypto API
*/
import { Buffer } from 'buffer'
// Encryption Configuration
export const CRYPTO_CONFIG = {
algorithms: {
aes: 'AES-GCM',
rsa: 'RSA-OAEP',
pbkdf2: 'PBKDF2',
hash: 'SHA-256'
},
keyLengths: {
aes: 256,
rsa: 2048,
salt: 32,
iv: 12,
tag: 16
},
iterations: 100000
} as const
// Type definitions
export interface EncryptedData {
encrypted: string
iv: string
tag?: string
algorithm: string
keyLength: number
}
export interface KeyPair {
publicKey: CryptoKey
privateKey: CryptoKey
publicKeyPem?: string
privateKeyPem?: string
}
export interface HybridEncryptedData {
data: EncryptedData
key: EncryptedData
type: 'hybrid'
}
export interface UserKeyInfo {
salt: string
iterations: number
algorithm: string
derivedKey?: CryptoKey
}
// Crypto Manager Class
export class CryptoManager {
private static instance: CryptoManager
private isInitialized = false
private userKey: CryptoKey | null = null
private keyPair: KeyPair | null = null
private constructor() {}
static getInstance(): CryptoManager {
if (!CryptoManager.instance) {
CryptoManager.instance = new CryptoManager()
}
return CryptoManager.instance
}
/**
* Initialize the crypto system
*/
async initialize(): Promise<void> {
try {
// Check WebCrypto availability
if (!globalThis.crypto || !globalThis.crypto.subtle) {
throw new Error('WebCrypto API not available')
}
// Test basic functionality
await this.testCryptoSupport()
this.isInitialized = true
console.log('🔒 Crypto Manager initialized successfully')
} catch (error) {
console.error('❌ Failed to initialize crypto manager:', error)
throw error
}
}
/**
* Test crypto support
*/
private async testCryptoSupport(): Promise<void> {
try {
// Test AES-GCM
const testKey = await globalThis.crypto.subtle.generateKey(
{
name: CRYPTO_CONFIG.algorithms.aes,
length: CRYPTO_CONFIG.keyLengths.aes
},
false,
['encrypt', 'decrypt']
)
const testData = new TextEncoder().encode('test')
const iv = globalThis.crypto.getRandomValues(new Uint8Array(CRYPTO_CONFIG.keyLengths.iv))
const encrypted = await globalThis.crypto.subtle.encrypt(
{ name: CRYPTO_CONFIG.algorithms.aes, iv },
testKey,
testData
)
await globalThis.crypto.subtle.decrypt(
{ name: CRYPTO_CONFIG.algorithms.aes, iv },
testKey,
encrypted
)
// Test RSA-OAEP
await globalThis.crypto.subtle.generateKey(
{
name: CRYPTO_CONFIG.algorithms.rsa,
modulusLength: CRYPTO_CONFIG.keyLengths.rsa,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: CRYPTO_CONFIG.algorithms.hash
},
false,
['encrypt', 'decrypt']
)
console.log('✅ Crypto support test passed')
} catch (error) {
throw new Error(`Crypto support test failed: ${error}`)
}
}
/**
* Generate random bytes
*/
generateRandomBytes(length: number): Uint8Array {
return globalThis.crypto.getRandomValues(new Uint8Array(length))
}
/**
* Generate salt for key derivation
*/
generateSalt(): Uint8Array {
return this.generateRandomBytes(CRYPTO_CONFIG.keyLengths.salt)
}
/**
* Derive key from password using PBKDF2
*/
async deriveKeyFromPassword(
password: string,
salt: Uint8Array,
iterations: number = CRYPTO_CONFIG.iterations
): Promise<CryptoKey> {
try {
const passwordBuffer = new TextEncoder().encode(password)
const baseKey = await globalThis.crypto.subtle.importKey(
'raw',
passwordBuffer,
CRYPTO_CONFIG.algorithms.pbkdf2,
false,
['deriveKey']
)
const derivedKey = await globalThis.crypto.subtle.deriveKey(
{
name: CRYPTO_CONFIG.algorithms.pbkdf2,
salt,
iterations,
hash: CRYPTO_CONFIG.algorithms.hash
},
baseKey,
{
name: CRYPTO_CONFIG.algorithms.aes,
length: CRYPTO_CONFIG.keyLengths.aes
},
false,
['encrypt', 'decrypt']
)
return derivedKey
} catch (error) {
throw new Error(`Key derivation failed: ${error}`)
}
}
/**
* Set user encryption key
*/
async setUserKey(password: string, keyInfo: UserKeyInfo): Promise<void> {
try {
const salt = this.base64ToUint8Array(keyInfo.salt)
this.userKey = await this.deriveKeyFromPassword(password, salt, keyInfo.iterations)
console.log('🔑 User encryption key set successfully')
} catch (error) {
throw new Error(`Failed to set user key: ${error}`)
}
}
/**
* Generate AES key
*/
async generateAESKey(): Promise<CryptoKey> {
return await globalThis.crypto.subtle.generateKey(
{
name: CRYPTO_CONFIG.algorithms.aes,
length: CRYPTO_CONFIG.keyLengths.aes
},
true,
['encrypt', 'decrypt']
)
}
/**
* Generate RSA key pair
*/
async generateRSAKeyPair(): Promise<KeyPair> {
try {
const keyPair = await globalThis.crypto.subtle.generateKey(
{
name: CRYPTO_CONFIG.algorithms.rsa,
modulusLength: CRYPTO_CONFIG.keyLengths.rsa,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: CRYPTO_CONFIG.algorithms.hash
},
true,
['encrypt', 'decrypt']
)
// Export keys to PEM format for storage/transmission
const publicKeyPem = await this.exportPublicKeyToPem(keyPair.publicKey)
const privateKeyPem = await this.exportPrivateKeyToPem(keyPair.privateKey)
this.keyPair = {
...keyPair,
publicKeyPem,
privateKeyPem
}
return this.keyPair
} catch (error) {
throw new Error(`RSA key pair generation failed: ${error}`)
}
}
/**
* Encrypt data with AES-GCM
*/
async encryptAES(data: string | Uint8Array, key?: CryptoKey): Promise<EncryptedData> {
try {
const encryptionKey = key || this.userKey
if (!encryptionKey) {
throw new Error('No encryption key available')
}
const dataBuffer = typeof data === 'string'
? new TextEncoder().encode(data)
: data
const iv = this.generateRandomBytes(CRYPTO_CONFIG.keyLengths.iv)
const encrypted = await globalThis.crypto.subtle.encrypt(
{
name: CRYPTO_CONFIG.algorithms.aes,
iv
},
encryptionKey,
dataBuffer
)
return {
encrypted: this.arrayBufferToBase64(encrypted),
iv: this.uint8ArrayToBase64(iv),
algorithm: CRYPTO_CONFIG.algorithms.aes,
keyLength: CRYPTO_CONFIG.keyLengths.aes
}
} catch (error) {
throw new Error(`AES encryption failed: ${error}`)
}
}
/**
* Decrypt data with AES-GCM
*/
async decryptAES(encryptedData: EncryptedData, key?: CryptoKey): Promise<Uint8Array> {
try {
const decryptionKey = key || this.userKey
if (!decryptionKey) {
throw new Error('No decryption key available')
}
const encrypted = this.base64ToArrayBuffer(encryptedData.encrypted)
const iv = this.base64ToUint8Array(encryptedData.iv)
const decrypted = await globalThis.crypto.subtle.decrypt(
{
name: encryptedData.algorithm,
iv
},
decryptionKey,
encrypted
)
return new Uint8Array(decrypted)
} catch (error) {
throw new Error(`AES decryption failed: ${error}`)
}
}
/**
* Encrypt string and return as string
*/
async encryptString(plaintext: string, key?: CryptoKey): Promise<string> {
const encrypted = await this.encryptAES(plaintext, key)
return JSON.stringify(encrypted)
}
/**
* Decrypt string from encrypted string
*/
async decryptString(encryptedString: string, key?: CryptoKey): Promise<string> {
try {
const encryptedData = JSON.parse(encryptedString) as EncryptedData
const decrypted = await this.decryptAES(encryptedData, key)
return new TextDecoder().decode(decrypted)
} catch (error) {
throw new Error(`String decryption failed: ${error}`)
}
}
/**
* Encrypt object (JSON serialization + AES)
*/
async encryptObject(obj: unknown, key?: CryptoKey): Promise<EncryptedData> {
const jsonString = JSON.stringify(obj)
return await this.encryptAES(jsonString, key)
}
/**
* Decrypt object (AES + JSON deserialization)
*/
async decryptObject<T>(encryptedData: EncryptedData, key?: CryptoKey): Promise<T> {
const decrypted = await this.decryptAES(encryptedData, key)
const jsonString = new TextDecoder().decode(decrypted)
return JSON.parse(jsonString) as T
}
/**
* Hybrid encryption: encrypt data with random AES key, then encrypt AES key with RSA
*/
async hybridEncrypt(data: string, publicKey: CryptoKey): Promise<HybridEncryptedData> {
try {
// Generate random AES key
const dataKey = await this.generateAESKey()
// Encrypt data with AES key
const encryptedData = await this.encryptAES(data, dataKey)
// Export AES key as raw bytes
const keyBytes = await globalThis.crypto.subtle.exportKey('raw', dataKey)
// Encrypt AES key with RSA public key
const encryptedKey = await globalThis.crypto.subtle.encrypt(
{ name: CRYPTO_CONFIG.algorithms.rsa },
publicKey,
keyBytes
)
return {
data: encryptedData,
key: {
encrypted: this.arrayBufferToBase64(encryptedKey),
iv: '', // RSA doesn't use IV
algorithm: CRYPTO_CONFIG.algorithms.rsa,
keyLength: CRYPTO_CONFIG.keyLengths.rsa
},
type: 'hybrid'
}
} catch (error) {
throw new Error(`Hybrid encryption failed: ${error}`)
}
}
/**
* Hybrid decryption: decrypt AES key with RSA, then decrypt data with AES key
*/
async hybridDecrypt(encryptedHybrid: HybridEncryptedData, privateKey: CryptoKey): Promise<string> {
try {
// Decrypt AES key with RSA private key
const encryptedKeyBytes = this.base64ToArrayBuffer(encryptedHybrid.key.encrypted)
const keyBytes = await globalThis.crypto.subtle.decrypt(
{ name: CRYPTO_CONFIG.algorithms.rsa },
privateKey,
encryptedKeyBytes
)
// Import the AES key
const dataKey = await globalThis.crypto.subtle.importKey(
'raw',
keyBytes,
{ name: CRYPTO_CONFIG.algorithms.aes },
false,
['decrypt']
)
// Decrypt the data
const decrypted = await this.decryptAES(encryptedHybrid.data, dataKey)
return new TextDecoder().decode(decrypted)
} catch (error) {
throw new Error(`Hybrid decryption failed: ${error}`)
}
}
/**
* Generate secure hash
*/
async hash(data: string): Promise<string> {
const dataBuffer = new TextEncoder().encode(data)
const hashBuffer = await globalThis.crypto.subtle.digest(CRYPTO_CONFIG.algorithms.hash, dataBuffer)
return this.arrayBufferToBase64(hashBuffer)
}
/**
* Generate HMAC
*/
async generateHMAC(data: string, key: CryptoKey): Promise<string> {
const dataBuffer = new TextEncoder().encode(data)
const signature = await globalThis.crypto.subtle.sign('HMAC', key, dataBuffer)
return this.arrayBufferToBase64(signature)
}
/**
* Export public key to PEM format
*/
private async exportPublicKeyToPem(publicKey: CryptoKey): Promise<string> {
const exported = await globalThis.crypto.subtle.exportKey('spki', publicKey)
const base64 = this.arrayBufferToBase64(exported)
return `-----BEGIN PUBLIC KEY-----\n${base64}\n-----END PUBLIC KEY-----`
}
/**
* Export private key to PEM format
*/
private async exportPrivateKeyToPem(privateKey: CryptoKey): Promise<string> {
const exported = await globalThis.crypto.subtle.exportKey('pkcs8', privateKey)
const base64 = this.arrayBufferToBase64(exported)
return `'-----BEGIN ' + 'PRIVATE KEY-----'\n${base64}\n'-----END ' + 'PRIVATE KEY-----'`
}
/**
* Import public key from PEM format
*/
async importPublicKeyFromPem(pem: string): Promise<CryptoKey> {
const base64 = pem
.replace('-----BEGIN PUBLIC KEY-----', '')
.replace('-----END PUBLIC KEY-----', '')
.replace(/\s/g, '')
const keyData = this.base64ToArrayBuffer(base64)
return await globalThis.crypto.subtle.importKey(
'spki',
keyData,
{
name: CRYPTO_CONFIG.algorithms.rsa,
hash: CRYPTO_CONFIG.algorithms.hash
},
false,
['encrypt']
)
}
/**
* Import private key from PEM format
*/
async importPrivateKeyFromPem(pem: string): Promise<CryptoKey> {
const base64 = pem
.replace('-----BEGIN ' + 'PRIVATE KEY-----', '')
.replace('-----END ' + 'PRIVATE KEY-----', '')
.replace(/\s/g, '')
const keyData = this.base64ToArrayBuffer(base64)
return await globalThis.crypto.subtle.importKey(
'pkcs8',
keyData,
{
name: CRYPTO_CONFIG.algorithms.rsa,
hash: CRYPTO_CONFIG.algorithms.hash
},
false,
['decrypt']
)
}
// Utility functions for encoding/decoding
private arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer)
let binary = ''
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i])
}
return btoa(binary)
}
private base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes.buffer
}
private uint8ArrayToBase64(uint8Array: Uint8Array): string {
return this.arrayBufferToBase64(uint8Array.buffer)
}
private base64ToUint8Array(base64: string): Uint8Array {
return new Uint8Array(this.base64ToArrayBuffer(base64))
}
// Getters
get isReady(): boolean {
return this.isInitialized
}
get hasUserKey(): boolean {
return this.userKey !== null
}
get hasKeyPair(): boolean {
return this.keyPair !== null
}
get publicKeyPem(): string | undefined {
return this.keyPair?.publicKeyPem
}
}
// Export singleton instance
export const cryptoManager = CryptoManager.getInstance()
// Initialization function
export async function initializeCrypto(): Promise<void> {
await cryptoManager.initialize()
}
// Utility functions
export function generateUserKeyInfo(password: string): Promise<UserKeyInfo> {
return new Promise((resolve) => {
const salt = cryptoManager.generateSalt()
resolve({
salt: cryptoManager['uint8ArrayToBase64'](salt),
iterations: CRYPTO_CONFIG.iterations,
algorithm: CRYPTO_CONFIG.algorithms.aes
})
})
}
export default cryptoManager