Skip to content

Instantly share code, notes, and snippets.

@prpanto
Created January 28, 2025 09:53
Show Gist options
  • Save prpanto/b89aad00f43661727f53750bafdc07b0 to your computer and use it in GitHub Desktop.
Save prpanto/b89aad00f43661727f53750bafdc07b0 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const crypto = require('crypto');
// Encryption settings
const algorithm = 'aes-256-cbc'; // Algorithm to use
const iterations = 100000; // Number of iterations for PBKDF2
const keyLength = 32; // Key length for AES-256
const ivLength = 16; // IV length for AES
// Function to derive a key and IV from a passphrase and salt
function deriveKeyAndIV(password, salt) {
// Derive the key using PBKDF2
const key = crypto.pbkdf2Sync(password, salt, iterations, keyLength, 'sha256');
const iv = key.subarray(0, ivLength); // Use the first 16 bytes as the IV
return { key, iv };
}
// Function to encrypt the file content
function encryptFile(filePath, password) {
try {
// Generate a random salt
const salt = crypto.randomBytes(16);
// Derive the key and IV from the passphrase and salt
const { key, iv } = deriveKeyAndIV(password, salt);
// Read the file data
const fileData = fs.readFileSync(filePath);
console.log(fileData)
// Create cipher
const cipher = crypto.createCipheriv(algorithm, key, iv);
// Encrypt the data
const encryptedData = Buffer.concat([cipher.update(fileData), cipher.final()]);
// console.log(encryptedData)
// Write the salt and encrypted data back to the file
fs.writeFileSync(filePath, Buffer.concat([salt, encryptedData]));
console.log('File encrypted successfully.');
} catch (error) {
console.error('Error during encryption:', error.message);
}
}
// Function to decrypt the file content
function decryptFile(filePath, password) {
try {
// Read the file data
const fileData = fs.readFileSync(filePath);
console.log(fileData)
// Extract the salt (first 16 bytes) and the encrypted data
const salt = fileData.subarray(0, 16);
const encryptedData = fileData.subarray(16);
// Derive the key and IV from the passphrase and extracted salt
const { key, iv } = deriveKeyAndIV(password, salt);
// Create decipher
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// Decrypt the data
const decryptedData = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
// console.log(decryptedData)
// Write the decrypted data back to the file
fs.writeFileSync(filePath, decryptedData);
console.log('File decrypted successfully.');
} catch (error) {
console.error('Error during decryption:', error.message);
}
}
// Example usage
const filePath = './image.jpeg'; // Replace with your file path
const password = 'this is my encryption password'; // Replace with your passphrase
// Encrypt the file
// encryptFile(filePath, password);
// Decrypt the file (to verify)
// decryptFile(filePath, password);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment