【问题标题】:How to encrypt a large dataset using python-gnupg without sucking up all the memory?如何在不占用所有内存的情况下使用 python-gnupg 加密大型数据集?
【发布时间】:2016-02-15 23:34:55
【问题描述】:

我在磁盘上有一个非常大的文本文件。假设它是 1 GB 或更多。还假设此文件中的数据每 120 个字符有一个 \n 字符。

我正在使用python-gnupg 对此文件进行加密。 由于文件太大,我无法一次将整个文件读入内存。

但是,我使用的gnupg.encrypt() 方法要求我一次发送所有数据——而不是分块发送。那么如何在不耗尽所有系统内存的情况下加密文件呢?

这里是一些示例代码:

import gnupg
gpg = gnupg.GPG(gnupghome='/Users/syed.saqibali/.gnupg/')

for curr_line in open("VeryLargeFile.txt", "r").xreadlines():
    encrypted_ascii_data = gpg.encrypt(curr_line, "recipient@gmail.com")
    open("EncryptedOutputFile.dat", "a").write(encrypted_ascii_data)

此示例生成无效的输出文件,因为我不能简单地将加密的 blob 连接到一个文件中。

【问题讨论】:

    标签: python encryption gnupg


    【解决方案1】:

    逐行加密会产生海量的OpenPGP文档,这不仅会使解密更加复杂,而且会大大增加文件大小和计算量。

    Python 的 GnuPG 模块还知道一个方法 encrypt_file,它接受一个流作为输入,并且知道可选的 output 参数以直接将结果写入文件。

    with open("VeryLargeFile.txt", "r") as infile:
        gpg.encrypt_file(
                infile, "recipient@example.org",
                output="EncryptedOutputFile.dat")
    

    这会导致流行为具有恒定且低内存要求。

    【讨论】:

      【解决方案2】:

      我在 open 命令中添加了一个“b”(二进制),它对我的​​代码非常有用。不过,由于某种原因,这种加密方式比通过 shell/bash 命令加密的速度要慢一半。

      【讨论】:

        猜你喜欢
        • 2016-09-02
        • 2013-02-11
        • 2021-04-15
        • 2022-07-25
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        • 2012-10-19
        • 2014-01-04
        相关资源
        最近更新 更多