Reputation: 992
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
Reputation: 8718
You seem to want to use it for two cases:
.pipe(output)
with .pipe(anotherStream)
.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