python读取加密的(使用gnupg)zip文件的内容,而不将文件解密到文件系 统中

问题描述 投票:1回答:1

借助于zipfile.ZipFile,我可以访问/读取zip文件中的文件,而无需实际提取到文件夹。

with zipfile.ZipFile('data.zip', 'rb') as zfile:
    with zfile.open('fil.dat', 'r') as dfile:
        csv_data = io.TextIOWrapper(dfile, encoding='utf-8')
        ....
        ....

现在,是否可以读取/访问加密的zip文件中的文件?使用gnupg对zip文件进行加密我有一种解决方法,可以解密和读取zip的内容,如下所示

import gnupg
gpg = gnupg.GPG()
with open('key.asc') as kfile:
    key = kfile.read()

gpg.import_keys(key)
with open('data.zip.gpg', 'rb') as gfile:
    gpg.decrypt_file(gfile, passphrase='password', output='data.zip')

这将在文件系统上创建一个新的解密zip文件,允许我读取/访问zip文件中的文件,并且每次使用后都必须删除该文件。是否有可能将zip文件解密为类似文件的对象并访问内容,而无需在文件系统上实际创建解密的zip文件?我尝试了以下类似操作,但失败了。

import gnupg
gpg = gnupg.GPG()
with open('key.asc') as kfile:
    key = kfile.read()
gpg.import_keys(key)

zip_file_obj = io.BytesIO()

with open('data.zip.gpg', 'rb') as gfile:
    gpg.decrypt_file(gfile, passphrase='password', output=zip_file_obj)

上面的代码失败,错误BytesIO类型不是有效的输入。对于我的用例,有没有一种方法可以完成此操作或任何其他python包装器/程序包?注意:我正在使用python 3.6错误:

Traceback (most recent call last):
  File "gptester.py", line 15, in <module>
    gpg.decrypt_file(gfile, passphrase='TESTTESTTEST', output=zip_file_obj)
  File "/usr/local/lib/python3.6/site-packages/gnupg/gnupg.py", line 1093, in decrypt_file
    if os.path.exists(output):
  File "/usr/local/lib/python3.6/genericpath.py", line 19, in exists
    os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not _io.BytesIO

编辑-II我从提供的建议中尝试了此代码

from io import BytesIO
from zipfile import ZipFile
import gnupg

with open('worker/key.asc') as kfile:
    key = kfile.read()

gpg = gnupg.GPG()
gpg.import_keys(key)
zip_file_obj = BytesIO()

with open('data.zip.gpg', 'rb') as gfile:
    decrypt_data = gpg.decrypt_file(gfile, passphrase='password')

zip_file_obj = BytesIO(decrypt_data)

错误:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.6/site-packages/gnupg/_meta.py", line 650, in _read_response
    result._handle_status(keyword, value)
  File "/usr/local/lib/python3.6/site-packages/gnupg/_parsers.py", line 1294, in _handle_status
    raise ValueError("Unknown status message: %r" % key)
ValueError: Unknown status message: 'PINENTRY_LAUNCHED'

Traceback (most recent call last):
  File "gptester.py", line 17, in <module>
    zip_file_obj = BytesIO(decrypt_data)
TypeError: a bytes-like object is required, not 'Crypt'
python gnupg
1个回答
0
投票

Documentation显示您可以执行

decrypted_data = gpg.decrypt_file(gfile, passphrase='password')

无需写入文件即可获取它。

要创建类似文件的对象,您需要decrypted_data.data

zip_file_obj = io.BytesIO(decrypted_data.data)

文档还提到str(decrypted_data)作为获取数据的方法。

© www.soinside.com 2019 - 2024. All rights reserved.