/**
* Encryption utilities for storing connection strings
*/
import crypto from 'crypto';
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const SALT_LENGTH = 64;
const TAG_LENGTH = 16;
export class EncryptionUtil {
private key: Buffer;
constructor(secret: string) {
// Derive a key from the secret
this.key = crypto.scryptSync(secret, 'salt', 32);
}
encrypt(text: string): string {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, this.key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const tag = cipher.getAuthTag();
// Combine iv + encrypted + tag
return iv.toString('hex') + ':' + encrypted + ':' + tag.toString('hex');
}
decrypt(encryptedText: string): string {
const parts = encryptedText.split(':');
const iv = Buffer.from(parts[0], 'hex');
const encrypted = parts[1];
const tag = Buffer.from(parts[2], 'hex');
const decipher = crypto.createDecipheriv(ALGORITHM, this.key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}