forked from googleapis/cloud-trace-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcredentials.ts
53 lines (45 loc) · 1.34 KB
/
credentials.ts
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
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import { createReadStream, createWriteStream } from 'fs';
export interface KeyAndIV {
key: string;
iv: string;
}
export async function encryptCredentials(filename: string): Promise<KeyAndIV> {
const key = randomBytes(32).toString('hex');
const iv = randomBytes(16).toString('hex');
const decipher = createCipheriv(
'aes-256-cbc',
Buffer.from(key, 'hex'),
Buffer.from(iv, 'hex')
);
const readStream = createReadStream(filename);
const writeStream = createWriteStream(`${filename}.enc`);
await new Promise((resolve, reject) => {
readStream
.on('error', reject)
.pipe(decipher)
.on('error', reject)
.pipe(writeStream)
.on('error', reject)
.on('finish', resolve);
});
return { key, iv };
}
export async function decryptCredentials({ key, iv }: KeyAndIV, filename: string) {
const decipher = createDecipheriv(
'aes-256-cbc',
Buffer.from(key, 'hex'),
Buffer.from(iv, 'hex')
);
const readStream = createReadStream(`${filename}.enc`);
const writeStream = createWriteStream(filename);
await new Promise((resolve, reject) => {
readStream
.on('error', reject)
.pipe(decipher)
.on('error', reject)
.pipe(writeStream)
.on('error', reject)
.on('finish', resolve);
});
}