【发布时间】:2020-06-18 15:12:18
【问题描述】:
所以我有一个应用程序可以下载一个包含一堆音频文件的 zip 文件夹。我想在下载时加密该 zip 文件,然后能够在应用程序中的某个其他位置解密该 zip 文件,以便将其提取。我有使用 Node 的 Crypto 包和 CTR 模式的 AES-256 进行加密和解密的基本逻辑,但在过程结束时我似乎无法获得可用的 zip 文件。
这是我用来下载 zip 文件的 http.get 请求
http.get(fileURI).on('response', function(res) {
res.on('data', function(chunk) {
let encryptedChunk = encrypt(chunk);
writeStream.write(encryptedChunk);
}).on('end', function() {
writeStream.end();
})
})
因此,get 请求会在下载数据时对其进行加密,并将其发送到对特定文件打开的 writeStream,然后在 zip 完成下载时结束 writestream。这似乎加密正确,因为我无法打开 zip 文件(弹出 Windows 无法打开文件夹错误)。
我的 encrypt 函数非常基本,在 http 请求中调用如下所示:
function encrypt(data) {
try {
let cipher = crypto.createCipher('aes-256-ctr', key); // key is a random string
let encrypted = Buffer.concat([cipher.update(new Buffer(data, "utf8")), cipher.final()]);
return encrypted;
} catch (exception) {
console.error(exception);
}
}
然后我有一个函数会创建一个尝试解密此文件的 readStream,它看起来像这样:
function decryptzip() {
// assume there are a bunch of necessary filepaths up here
let readStream = fs.createReadStream(downloadedZipFilePath);
let writeStream = fs.createWriteStream(newDecryptedZipFilePath);
readStream.on('data', (chunk) => {
let decryptedChunk = decrypt(chunk);
writeStream.write(decryptedChunk); // the goal of this write stream is to have a usable zip file once it closes
}).on('finish', () => {
writeStream.end();
})
}
然后我的实际解密函数如下所示:
function decrypt(data) {
try {
let decipher = crypto.createDecipher('aes-256-ctr', key); // same key used in encrypt
let decrypted = Buffer.concat([decipher.update(data), decipher.final()]);
return decrypted;
} catch (exception) {
console.error(exception);
}
}
这些加密和解密函数都可以使用纯文本查找,但“解密”的 zip 文件仍然无法使用,当我尝试查看里面的内容时,会出现“Windows 无法打开文件夹错误”。我真的不知道我在这方面做什么,所以任何帮助都将不胜感激,我很迷茫哈哈。
【问题讨论】:
标签: javascript node.js encryption cryptography node-crypto