Encrypt / Decrypt files with Node.JS

Very simple example on how to encrypt and decrypt files using Node.JS and AES encryption algorithm.

Encrypt / Decrypt files with Node.JS

Very simple example on how to do that. No rocket science here.

#!/usr/bin/env node

/*
 * SYNTAX:
 * 
 * node aes.js -e <file_name> <password> 
 * node aes.js --encrypt <file_name> <password> 
 * 
 * node aes.js -d <file_name> <password> 
 * node aes.js --decrypt <file_name> <password> 
 * 
 */

const crypto = require('crypto');
const fs = require('fs');

// --- Functions --------------------
function encryptFile(fileName, password) {

    let iv = crypto.createHash("sha1").update(password, "utf8").digest().subarray(0, 16); // 16 bytes

    let cipher = crypto.createCipheriv("aes-256-cbc", crypto.createHash("sha256").update(password, "utf8").digest(), iv);

    let input = fs.createReadStream(fileName);
    let output = fs.createWriteStream(fileName + '.enc');

    input.pipe(cipher).pipe(output);

    output.on('finish', function () {
        console.log('>>> File ' + fileName + ' encrypted as ' + fileName + '.enc');
        fs.unlinkSync(fileName);
    });
}

function decryptFile(fileName, password) {

    let iv = crypto.createHash("sha1").update(password, "utf8").digest().subarray(0, 16); // 16 bytes

    let decipher = crypto.createDecipheriv("aes-256-cbc", crypto.createHash("sha256").update(password, "utf8").digest(), iv);

    let input = fs.createReadStream(fileName);
    let output = fs.createWriteStream(fileName.replace('.enc', ''));

    input.pipe(decipher).pipe(output);

    output.on('finish', function () {
        console.log('<<< File ' + fileName + ' decrypted as ' + fileName.replace('.enc', ''));
        fs.unlinkSync(fileName);
    });
}

function main() {

    let inputFile = process.cwd() + "/" + process.argv[3];
    let key = process.argv[4];

    try {

        if (process.argv[2] === "-e" || process.argv[2] === "--encrypt") {

            encryptFile(inputFile, key);

        } else if (process.argv[2] === "-d" || process.argv[2] === "--decrypt") {

            decryptFile(inputFile, key);

        } else {

            console.log("/!\\ Something went wrong.");
        }

    } catch (err) {

        console.log(err.message);
    }
}

// --- Program --------------------

main();

You can copy and paste the above code inside a file called aes.js and start playing with it.