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.
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.
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.
isdir() or a file with TarInfo. isfile() . Similarly you can determine whether a file is a zip file using zipfile. is_zipfile() .
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With