← back to AbramsOS
lib/crypto.js
28 lines
const crypto = require('crypto');
function getKey() {
const hex = process.env.ENCRYPTION_KEY;
if (!hex || hex.length < 64) {
throw new Error('ENCRYPTION_KEY env var must be 32 bytes (64 hex chars). Generate via `openssl rand -hex 32` and route via /secrets.');
}
return Buffer.from(hex.slice(0, 64), 'hex');
}
function encrypt(plaintext) {
const key = getKey();
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return { ciphertext, iv, tag };
}
function decrypt(ciphertext, iv, tag) {
const key = getKey();
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
}
module.exports = { encrypt, decrypt };