NodeJS中gzip压缩后PGP加密的文件解密后格式无效问题
解密后gzip格式无效的修复方案
问题出在你把压缩后的二进制Buffer直接转成字符串,传给了openpgp的text参数——这会彻底破坏gzip的二进制结构。text参数是用来处理纯文本的,二进制数据转字符串时会因为编码问题丢失或篡改字节,导致解密后的文件不再是有效的gzip格式。
修复步骤
- 改用openpgp的二进制消息类型:放弃
text参数,直接用binary参数传递压缩后的Buffer,避免编码转换损坏数据。 - 调整加密逻辑:确保openpgp处理的是原始二进制gzip数据,而非转码后的字符串。
修复后的完整代码
zlib.gzip("Hello World", async (err, compressedData) => { if (err) { console.error('Error compressing data:', err); return; } try { // 关键修改:用binary参数传递压缩后的Buffer,而非转成字符串 const message = await openpgp.createMessage({ binary: compressedData }); const publicKeyObj = await openpgp.readKey({ armoredKey: publicKeyForEncryption }); const encryptedData = await openpgp.encrypt({ message, encryptionKeys: publicKeyObj }); // 保存加密后的armored数据到文件 fs.writeFile('/path_to_file/output.txt.gz.gpg', encryptedData, (error) => { if (error) { console.error('Error saving compressed data to file:', error); return; } console.log('Data compressed and saved to file successfully.'); }); } catch (error) { console.error('Error encrypting data:', error); } });
额外说明
- 解密时需要对应处理二进制消息:解密后会得到原始的gzip Buffer,直接用
zlib.gunzip解压就能恢复出"Hello World"。 - openpgp加密二进制消息后输出的仍是armored格式字符串,直接写入文件即可,无需额外处理编码。
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

