3

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

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 而不是先读取整个文件?

4

1 回答 1

3

我知道您可以多次调用 .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() )
于 2012-10-03T16:11:13.277 回答