From 15e5f2fa87ee50c51e90482d18577a796ca4ee5c Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Tue, 3 Dec 2024 14:58:55 +0700 Subject: [PATCH] Create encryption.js --- src/security/encryption.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/security/encryption.js 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 };