gpt4 book ai didi

javascript - Node.js 加密和解密是文件大小加倍

转载 作者:行者123 更新时间:2023-11-30 20:12:03 27 4
gpt4 key购买 nike

我正在创建一个可以加密和解密图像文件的 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);

如何修复图像损坏和文件大小加倍?

最佳答案

你正试图在密码完成之前对其进行解密。如果等到pipe完成再读取加密文件,应该不会出现乱码:

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

关于javascript - Node.js 加密和解密是文件大小加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52306611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com