使用PGPy解密PGP加密文件后生成的PDF损坏,寻求排查方案
导致解密后PDF损坏的可能原因及解决方法
1. 解密内容类型错误(最可能)
你的加密源文件是sachin.pdf_enfos.zip.pgp,说明被加密的是ZIP压缩包,而非直接的PDF文件。你解密后直接将内容写入.pdf后缀的文件,相当于把ZIP数据当成PDF格式存储,自然会被识别为损坏文件。
解决方法:
解密后先保存为ZIP文件,再解压获取里面的PDF:
from pgpy import PGPKey, PGPMessage import zipfile privateKey, _ = PGPKey.from_file(str("/Users/shashank/devroot/home/keys/0/pvt.txt")) ENC_FILE = '/Users/shashank/devroot/sachin.pdf_enfos.zip.pgp' encrypted_message = PGPMessage.from_file(ENC_FILE) with privateKey.unlock('passphrase'): decrypted_message = privateKey.decrypt(encrypted_message) # 先保存为ZIP文件 with open("/Users/shashank/Downloads/test.zip", "wb") as f: f.write(decrypted_message.data) # 解压ZIP获取PDF with zipfile.ZipFile("/Users/shashank/Downloads/test.zip", 'r') as zip_ref: zip_ref.extractall("/Users/shashank/Downloads/")
2. PGPy解密后数据获取方式错误
PGPy中,decrypted_message.message主要用于获取文本类型的解密内容,对于二进制数据(如ZIP、PDF),应使用decrypted_message.data属性。如果用message处理二进制数据,可能会因字符串编码/解码操作破坏字节流,导致文件损坏。
修改代码中的数据获取逻辑:
# 替换原message = decrypted_message.message message = decrypted_message.data
3. 密钥或解密过程的隐性问题
- 验证私钥有效性:可以通过打印
privateKey.fingerprint确认私钥是否完整读取。 - 确认密码正确性:如果密码错误,PGPy可能不会抛出明确异常,但解密内容会是乱码。可检查解密后字节流的开头是否符合ZIP格式(ZIP文件起始字节通常为
b'PK\x03\x04')。
内容的提问来源于stack exchange,提问作者Shashank
相关产品推荐
相关产品推荐

