-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathstream.ts
More file actions
51 lines (42 loc) · 1.68 KB
/
Copy pathstream.ts
File metadata and controls
51 lines (42 loc) · 1.68 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
import { Transform } from 'stream';
import crypto from 'crypto';
const ALGORITHM = 'aes-256-gcm';
export interface EncryptionStreamResult {
stream: Transform;
getAuthTag: () => Buffer;
iv: Buffer;
}
/**
* Creates a transform stream for encrypting data using AES-256-GCM.
* It automatically generates a random IV.
*
* @param key The 32-byte encryption key.
* @returns An object containing the transform stream, the generated IV, and a function to retrieve the auth tag (available after stream end).
*/
export function createEncryptionStream(key: Buffer): EncryptionStreamResult {
if (key.length !== 32) {
throw new Error(`Invalid key length: ${key.length}. Key must be 32 bytes for AES-256-GCM.`);
}
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
// The auth tag is only available after final() has been called on the cipher.
// The caller must wait for the stream to finish before calling this.
const getAuthTag = () => cipher.getAuthTag();
return { stream: cipher, getAuthTag, iv };
}
/**
* Creates a transform stream for decrypting data using AES-256-GCM.
*
* @param key The 32-byte encryption key.
* @param iv The initialization vector used during encryption.
* @param authTag The authentication tag generated during encryption.
* @returns A transform stream that decrypts the data.
*/
export function createDecryptionStream(key: Buffer, iv: Buffer, authTag: Buffer): Transform {
if (key.length !== 32) {
throw new Error(`Invalid key length: ${key.length}. Key must be 32 bytes for AES-256-GCM.`);
}
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(authTag);
return decipher;
}