gnupg - 解密为 Python bytesio 流

问题描述 投票:0回答:2

如何选择 stream 作为

decrypt_file
gnupg
操作的输出?

文档和代码似乎表明这是不可能的。如果我是正确的(见下文),可以采取哪些解决方法?

~~~

文档似乎表明这是不可能的:

decrypt_file(filename, always_trust=False, passphrase=None, output=None)¶

with output (str) – 将解密的输出写入的文件名。”

~~~

打开代码,我看到:

def decrypt_file(self, file, always_trust=False, passphrase=None,
                 output=None, extra_args=None):
    args = ["--decrypt"]
    if output:  # write the output to a file with the specified name
        self.set_output_without_confirmation(args, output)
    if always_trust:  # pragma: no cover
        args.append("--always-trust")
    if extra_args:
        args.extend(extra_args)
    result = self.result_map['crypt'](self)
    self._handle_io(args, file, result, passphrase, binary=True)
    logger.debug('decrypt result: %r', result.data)
    return result

指向

set_output_without_confirmation
,确认这个想法是你传递了一个字符串文件名:

def set_output_without_confirmation(self, args, output):
    "If writing to a file which exists, avoid a confirmation message."
    if os.path.exists(output):
        # We need to avoid an overwrite confirmation message
        args.extend(['--yes'])
    args.extend(['--output', no_quote(output)])
python encryption gnupg bytesio
2个回答
0
投票

要将解密的数据输出到变量,请使用

decrypt
而不是
decrypt_file
,如“解密字符串”段落中的此处所示。

原来的代码:

status = gpg.decrypt_file(input_file, passphrase='my_passphrase', output='my_output_file')

替换为:

decrypted_data = gpg.decrypt(input_file.read(), passphrase='my_passphrase')
# decrypted_data.data contains the data
decrypted_stream = io.BytesIO(decrypted_data.data)
# this is py3, in py2 BytesIO is imported from BytesIO

作为 csv 数据的特定用例的示例,在此 SO 帖子的基础上,您可以执行以下操作:

my_df = pandas.read_csv(decrypted_stream)

0
投票

看起来您可能正在使用 python-gnupg 库。我刚刚从 https://groups.google.com/g/python-gnupg/c/Jo9mFtQEiaU/m/Hbvj1Q8rAQAJ 了解到,有一个

gpg.on_data
回调可以注册,可以对数据进行分块/“流式传输”。

将其与 fsspec 或 smart_open 或任何流结合起来,就可以很容易地以流方式解密,而不是将其全部保留在内存中。

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