Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a zip file is encrypted using python's standard library zipfile?

I am using python's standard library, zipfile, to test an archive:

zf = zipfile.ZipFile(archive_name)
if zf.testzip()==None: checksum_OK=True

And I am getting this Runtime exception:

File "./packaging.py", line 36, in test_wgt
    if zf.testzip()==None: checksum_OK=True
  File "/usr/lib/python2.7/zipfile.py", line 844, in testzip
    f = self.open(zinfo.filename, "r")
  File "/usr/lib/python2.7/zipfile.py", line 915, in open
    "password required for extraction" % name
RuntimeError: File xxxxx/xxxxxxxx.xxx is encrypted, password required for extraction

How can I test, before I run testzip(), if the zip is encrypted? I didn't found an exception to catch that would make this job simpler.

like image 562
Eduard Florinescu Avatar asked Aug 20 '12 13:08

Eduard Florinescu


People also ask

What does ZIP file ZIP file do?

Python's zipfile is a standard library module intended to manipulate ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data.

Is a ZIP file encrypted?

ZIP Application Note. Encryption is applied to files that are being zipped. This encryption is added after compression and does not affect any other associated data. Data in a Zip file is encrypted byte-for-byte.

How do you check if a file is a ZIP file in Python?

isdir() or a file with TarInfo. isfile() . Similarly you can determine whether a file is a zip file using zipfile. is_zipfile() .


1 Answers

A quick glance at the zipfile.py library code shows that you can check the ZipInfo class's flag_bits property to see if the file is encrypted, like so:

zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
    is_encrypted = zinfo.flag_bits & 0x1 
    if is_encrypted:
        print '%s is encrypted!' % zinfo.filename

Checking to see if the 0x1 bit is set is how the zipfile.py source sees if the file is encrypted (could be better documented!) One thing you could do is catch the RuntimeError from testzip() then loop over the infolist() and see if there are encrypted files in the zip.

You could also just do something like this:

try:
    zf.testzip()
except RuntimeError as e:
    if 'encrypted' in str(e):
        print 'Golly, this zip has encrypted files! Try again with a password!'
    else:
        # RuntimeError for other reasons....
like image 57
Zachary Hamm Avatar answered Oct 10 '22 21:10

Zachary Hamm