Node.js加密和解密使文件大小加倍

时间:2018-09-13 04:22:00

标签: javascript node.js encryption

我正在创建一个可以加密和解密图像文件的Node.js应用程序。但是,当我运行代码时,会得到不同的结果:有时解密后的图像看起来像原始图像在顶部,但下半部分看起来已损坏,有时解密后的图像完全存在,但看起来像被严重压缩,有时解密后的图像也是如此腐败打开。这是image演示的。这些结果唯一的共同点是加密和解密的图像是原始图像文件大小的两倍。

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

var path = 'C:\\Users\\' + windowsUserName + '\\Desktop\\image';
    var fileExtension = '.jpg';
    var password = '1234';
    var algorithm = 'aes-256-cbc';

    var image = fs.createReadStream(path + fileExtension);

    var encryptedImage = fs.createWriteStream(path + ' encrypted' + fileExtension);
    var decryptedImage = fs.createWriteStream(path + ' decrypted' + fileExtension);

    var encrypt = crypto.createCipher(algorithm, password);
    var decrypt = crypto.createDecipher(algorithm, password);

    image.pipe(encrypt).pipe(encryptedImage);
    image.pipe(encrypt).pipe(decrypt).pipe(decryptedImage);

如何解决图像损坏和文件大小加倍的问题?

1 个答案:

答案 0 :(得分:1)

您正在尝试解密密码,然后再解密。如果您等到管道完成并读取加密的文件,则不应乱码:

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

var path = 'file path';
    var fileExtension = '.jpg';
    var password = '1234';
    var algorithm = 'aes-256-cbc';

    var image = fs.createReadStream(path + fileExtension);
    var encryptedImage = fs.createWriteStream(path + ' encrypted' + fileExtension);
    var encrypt = crypto.createCipher(algorithm, password);
    image.pipe(encrypt).pipe(encryptedImage);

    encryptedImage.on("finish", function(){
        var decrypt = crypto.createDecipher(algorithm, password);
        var decryptedImage = fs.createWriteStream(path + ' decrypted' + fileExtension);
        var encryptedImage = fs.createReadStream(path + ' encrypted' + fileExtension);
        encryptedImage.pipe(decrypt).pipe(decryptedImage);
    })