File size: 1,997 Bytes
c7fbc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 crypto from 'crypto';

const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || ''; // Must be 32 bytes (64 hex characters)
const IV_LENGTH = 16; // For AES, this is always 16

export function encrypt(text: string): string {
    if (!ENCRYPTION_KEY) {
        throw new Error("ENCRYPTION_KEY not set in environment variables");
    }
    // Check key length (hex string should be 64 chars for 32 bytes, or 32 chars if utf8... standard is hex)
    // Actually, let's assume the user provides a 32-byte hex string.
    const keyBuffer = Buffer.from(ENCRYPTION_KEY, 'hex');

    if (keyBuffer.length !== 32) {
        throw new Error("ENCRYPTION_KEY must be a 32-byte hex string (64 characters)");
    }

    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv('aes-256-cbc', keyBuffer, iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);

    return iv.toString('hex') + ':' + encrypted.toString('hex');
}

export function decrypt(text: string): string {
    if (!ENCRYPTION_KEY) {
        throw new Error("ENCRYPTION_KEY not set in environment variables");
    }

    // Check if text is in valid format (iv:encrypted)
    const parts = text.split(':');
    if (parts.length !== 2) {
        // Fallback: If not formatted correctly, maybe it's not encrypted yet?
        // Or return text as is if we want to support transition period (risky but practical)
        // For now, let's error to be safe, or check complexity.
        // Assuming strict security:
        throw new Error("Invalid encrypted text format");
    }

    const keyBuffer = Buffer.from(ENCRYPTION_KEY, 'hex');
    const iv = Buffer.from(parts[0], 'hex');
    const encryptedText = Buffer.from(parts[1], 'hex');

    const decipher = crypto.createDecipheriv('aes-256-cbc', keyBuffer, iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);

    return decrypted.toString();
}