diff --git a/src/security/encryption.js b/src/security/encryption.js new file mode 100644 index 000000000..c9dc22a06 --- /dev/null +++ b/src/security/encryption.js @@ -0,0 +1,27 @@ +// src/security/encryption.js +const crypto = require('crypto'); +require('dotenv').config(); + +const ALGORITHM = 'aes-256-cbc'; +const KEY = crypto.scryptSync(process.env.ENCRYPTION_KEY, 'salt', 32); +const IV_LENGTH = 16; // For AES, this is always 16 + +function encrypt(text) { + const iv = crypto.randomBytes(IV_LENGTH); + const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv); + let encrypted = cipher.update(text, 'utf8', 'hex'); + encrypted += cipher.final('hex'); + return iv.toString('hex') + ':' + encrypted; +} + +function decrypt(encryptedText) { + const parts = encryptedText.split(':'); + const iv = Buffer.from(parts.shift(), 'hex'); + const encryptedTextBuffer = Buffer.from(parts.join(':'), 'hex'); + const decipher = crypto.createDecipheriv(ALGORITHM, KEY, iv); + let decrypted = decipher.update(encryptedTextBuffer, 'hex', 'utf8'); + decrypted += decipher.final('utf8'); + return decrypted; +} + +module.exports = { encrypt, decrypt };