-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryptionUtils.ts
More file actions
27 lines (20 loc) · 979 Bytes
/
encryptionUtils.ts
File metadata and controls
27 lines (20 loc) · 979 Bytes
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
import crypto from 'crypto';
import 'dotenv/config';
const IV_LENGTH = 16; // AES block size
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY!; // Must be 256 bits (32 characters)
export function encrypt(text: string) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([ encrypted, cipher.final() ]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
}
export function decrypt(text: string) {
const textParts = text.split(':');
const iv = Buffer.from(textParts.shift()!, 'hex');
const encryptedText = Buffer.from(textParts.join(':'), 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([ decrypted, decipher.final() ]);
return decrypted.toString();
}