简体   繁体   中英

How to strip password encryption from zipfile with Python

I have an use case where I need to strip decryption of password protected zip file attached to an email, and replace it with the same zip file unencrypted. What I have so far:

import zipfile
import StringIO

...

if part.get_content_type() == "application/zip":
    encrypted_string = part.get_payload().decode("base64")
    encrypted_zip = zipfile.ZipFile(StringIO(encrypted_string))
    encrypted_zip.setpassword("password")

I know that the zip file is now decrypted as I can do encrypted_zip.namelist() and it works. Now that I have regular zip in the var encrypted_zip, I would just like to base64 encode it and replace the payload of the current attachment and move forward to next attachment. However, ZipFile does not have ".to_string()" method which i could use to re-encode it.

How do I achieve this?

You can create a temporary archive to get rid of the password :

import zipfile
import StringIO


path = "dev.zip"   
encrypted_zip = zipfile.ZipFile( path  )
encrypted_zip.setpassword("pass")
print encrypted_zip.namelist()

with zipfile.ZipFile('spam.zip', 'w') as myzip:
    for nested_file in encrypted_zip.namelist():
        myzip.write(encrypted_zip.read(nested_file))

The script copy files for the password-protected archive 'dev.zip' into the uncrypted archive 'spam.zip'. ( do not forget to destroy the archive after).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM