Skip to content

Commit

Permalink
Create encryption.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Dec 3, 2024
1 parent 05b1c12 commit 15e5f2f
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/security/encryption.js
Original file line number Diff line number Diff line change
@@ -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 };

0 comments on commit 15e5f2f

Please sign in to comment.