pythoniopython-zipfile

Adding Password to Zip file with BytesIO


I am working on a project in which I need to zip a Word document and then upload the file to a Blob Storage in Azure with a password on the zip file. At this point in time I have managed to get the doc file into the zip and onto the Blob Storage using BytesIO but I can't password protect the zip.

I am using the following code to Zip the Word Document and upload to Blob Storage:

        zip_buffer = BytesIO()
        with zipfile.ZipFile(zip_buffer, "w") as zip_file:
            zip_file.writestr(filename, doc_stream.getvalue())
            zip_file.setpassword(b"12345")
            zip_file.close()

        zip_client.upload_blob(zip_buffer.getvalue(), overwrite=True)

Solution

  • Install pyzipper: pip install pyzipper

    import pyzipper
    from io import BytesIO
    from azure.storage.blob import BlobServiceClient
    
    zip_buffer = BytesIO()
    password = b"12345"
    
    with pyzipper.AESZipFile(zip_buffer, "w", compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zip_file:
        zip_file.setpassword(password)
        zip_file.writestr(filename, doc_stream.getvalue())
    
    zip_buffer.seek(0) 
    zip_client.upload_blob(zip_buffer.getvalue(), overwrite=True)