aadi1295
aadi1295

Reputation: 992

NodeJs AES File Decryption to a Stream

I am encrypting a file in C# and decrypting it in Node.js using AES. The following example works fine but it writes the decrypted file to `output_dec.xml', but I want to write the decrypted output to a variable or stream.

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

try {

    const password = "McQfTjWnZr4u7x!A";
    const KEY = Buffer.from(password, "utf8");
    const IV = Buffer.from(password, "utf8");

    var decipher = crypto.createDecipheriv('aes-128-cbc', KEY, IV);
    var input = fs.createReadStream(file);
    var output = fs.createWriteStream("output_dec.xml");
    input.pipe(decipher).pipe(output);

    output.on('finish', function () {
        console.log('Decrypted file written to disk!');
    });
}
catch (e) {
    console.log(e);
}

Upvotes: 0

Views: 1295

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

You seem to want to use it for two cases:

  • Output it to another stream. In which case simply replace .pipe(output) with .pipe(anotherStream).
  • Output to a variable. In which case you can read the data from input.pipe(decipher) like this:
const crypto = require("crypto");
const fs = require('fs');

try {

    const password = "McQfTjWnZr4u7x!A";
    const KEY = Buffer.from(password, "utf8");
    const IV = Buffer.from(password, "utf8");

    var decipher = crypto.createDecipheriv('aes-128-cbc', KEY, IV);
    var input = fs.createReadStream(file);
    const deciphered = input.pipe(decipher);
    let data = '';
    deciphered.on('data', chunk => data += chunk);
    deciphered.on('end', () => {
        console.log('Decrypted file stored in data!');
        // Decrypted file in `data`
    });
    deciphered.on('error', (e) => {
        console.error('Error:', e);
    });
    // Can't use `data` here yet (need to wait for 'end' event)
}
catch (e) {
    console.log(e);
}

Upvotes: 1

Related Questions