[ACCEPTED]-How to check if a zip file is encrypted using python's standard library zipfile?-encryption

Accepted answer
Score: 16

A quick glance at the zipfile.py library code shows that you can check 10 the ZipInfo class's flag_bits property to 9 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 8 to see if the 0x1 bit is set is how the 7 zipfile.py source sees if the file is encrypted 6 (could be better documented!) One thing 5 you could do is catch the RuntimeError from 4 testzip() then loop over the infolist() and 3 see if there are encrypted files in the 2 zip.

You could also just do something like 1 this:

except RuntimeError as e:
    if 'encrypted' in str(e):
        print 'Golly, this zip has encrypted files! Try again with a password!'
        # RuntimeError for other reasons....
Score: 0

If you want to catch an exception, you can 1 write this:

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

More Related questions