【问题标题】:Encrypt file using M2Crypto使用 M2Crypto 加密文件
【发布时间】:2012-10-03 15:36:09
【问题描述】:

众所周知,我可以读取内存中的整个文件内容并使用以下代码对其进行加密。

contents = fin.read()
cipher = M2Crypto.EVP.Cipher(alg="aes_128_cbc", key = aes_key, iv = aes_iv, op = 1)
encryptedContents = cipher.update(contents)
encryptedContents += cipher.final()

但是如果文件很大怎么办,有没有办法让我将输入流传递给 M2Crypto 而不是先读取整个文件?

【问题讨论】:

  • 我认为您不能将流传递给它。但是,如果我冒昧地猜测一下,您应该能够使用固定大小的缓冲区,将文件读入其中,并通过.update() 继续运行它,它会吐出加密的块。 .final() 看起来像是为结尾创建填​​充的方法。

标签: python encryption m2crypto


【解决方案1】:

我了解到您可以多次调用 .update(data)。

为了最大限度地减少内存使用并使用文件进行输出,您应该能够做到:

cipher = M2Crypto.EVP.Cipher(alg="aes_128_cbc", key = aes_key, iv = aes_iv, op = 1)
encrypted_contents_file = open(outfile_name, "w")

while True:
    buf = fin.read(1024)
    if not buf:
        break
    encrypted_contents_file.write(cipher.update(buf))

encrypted_contents_file.write( cipher.final() )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多