NodeJs AES 文件解密到流

NodeJs AES File Decryption to a Stream

我正在使用 C# 加密文件并使用 AES 在 Node.js 中解密它。 以下示例工作正常,但它将解密文件写入“output_dec.xml”,但我想将解密输出写入变量或流。

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);
}

您似乎想在两种情况下使用它:

  • 输出到另一个流。在这种情况下,只需将 .pipe(output) 替换为 .pipe(anotherStream).
  • 输出到一个变量。在这种情况下,您可以像这样从 input.pipe(decipher) 读取数据:
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);
}