Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt file using M2Crypto

It is known that I can read the whole file content in memory and encrypt it using the following code.

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()

But what if the file size is large, is there a way for me to pass the input stream to M2Crypto instead of reading the whole file first?

like image 480
Bear Avatar asked Dec 06 '25 01:12

Bear


1 Answers

I understood that you can call .update(data) multiple times.

To minimise memory usage and use a file for output you should be able to do:

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() )
like image 134
Alastair McCormack Avatar answered Dec 08 '25 15:12

Alastair McCormack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!