2

I am trying to read a password protected word document on Python using zipfile. The following code works with a non-password protected document, but gives an error when used with a password protected file.

try:
    from xml.etree.cElementTree import XML
except ImportError:
    from xml.etree.ElementTree import XML
import zipfile

psw = "1234"

WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'

def get_docx_text(path):

    document = zipfile.ZipFile(path, "r")
    document.setpassword(psw)
    document.extractall()
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.getiterator(PARA):
        texts = [node.text
                 for node in paragraph.getiterator(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return '\n\n'.join(paragraphs)

When running get_docx_text() with a password protected file, I received the following error:

Traceback (most recent call last):

  File "<ipython-input-15-d2783899bfe5>", line 1, in <module>
runfile('/Users/username/Workspace/Python/docx2txt.py', wdir='/Users/username/Workspace/Python')

  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 680, in runfile
execfile(filename, namespace)

  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)

  File "/Users/username/Workspace/Python/docx2txt.py", line 41, in <module>
x = get_docx_text("/Users/username/Desktop/file.docx")

  File "/Users/username/Workspace/Python/docx2txt.py", line 23, in get_docx_text
document = zipfile.ZipFile(path, "r")

  File "zipfile.pyc", line 770, in __init__

  File "zipfile.pyc", line 811, in _RealGetContents

BadZipfile: File is not a zip file

Does anyone have any advice to get this code to work?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Xander
  • 593
  • 1
  • 5
  • 19
  • 2
    Encrypted docx files are regular (non-password protected) zip files. The encryption is done to the contents of the zip file, it doesn't use zip's password protection system. Ref https://forum.openoffice.org/en/forum/viewtopic.php?f=5&t=71391 – Tom Dalton Apr 18 '15 at 19:22

1 Answers1

1

I don't think this is an encryption problem, for two reasons:

  1. Decryption is not attempted when the ZipFile object is created. Methods like ZipFile.extractall, extract, and open, and read take an optional pwd parameter containing the password, but the object constructor / initializer does not.

  2. Your stack trace indicates that the BadZipFile is being raised when you create the ZipFile object, before you call setpassword:

    document = zipfile.ZipFile(path, "r")

I'd look carefully for other differences between the two files you're testing: ownership, permissions, security context (if you have that on your OS), ... even filename differences can cause a framework to "not see" the file you're working on.

Also --- the obvious one --- try opening the encrypted zip file with your zip-compatible command of choice. See if it really is a zip file.

I tested this by opening an encrypted zip file in Python 3.1, while "forgetting" to provide a password. I could create the ZipFile object (the variable zfile below) without any error, but got a RuntimeError --- not a BadZipFile exception --- when I tried to read a file without providing a password:

Traceback (most recent call last):
  File "./zf.py", line 35, in <module>
    main()
  File "./zf.py", line 29, in main
    print_checksums(zipfile_name)
  File "./zf.py", line 22, in print_checksums
    for checksum in checksum_contents(zipfile_name):
  File "./zf.py", line 13, in checksum_contents
    inner_file = zfile.open(inner_filename, "r")
  File "/usr/lib64/python3.1/zipfile.py", line 903, in open
    "password required for extraction" % name)
RuntimeError: File apache.log is encrypted, password required for extraction

I was also able to raise a BadZipfile exception, once by trying to open an empty file and once by trying to open some random logfile text that I'd renamed to a ".zip" extension. The two test files produced identical stack traces, down to the line numbers.

Traceback (most recent call last):
  File "./zf.py", line 35, in <module>
    main()
  File "./zf.py", line 29, in main
    print_checksums(zipfile_name)
  File "./zf.py", line 22, in print_checksums
    for checksum in checksum_contents(zipfile_name):
  File "./zf.py", line 10, in checksum_contents
    zfile = zipfile.ZipFile(zipfile_name, "r")
  File "/usr/lib64/python3.1/zipfile.py", line 706, in __init__
    self._GetContents()
  File "/usr/lib64/python3.1/zipfile.py", line 726, in _GetContents
    self._RealGetContents()
  File "/usr/lib64/python3.1/zipfile.py", line 738, in _RealGetContents
    raise BadZipfile("File is not a zip file")
zipfile.BadZipfile: File is not a zip file

While this stack trace isn't exactly the same as yours --- mine has a call to _GetContents, and the pre-3.2 "small f" spelling of BadZipfile --- but they're close enough that I think this is the kind of problem you're dealing with.

Kevin J. Chase
  • 3,856
  • 4
  • 21
  • 43
  • Thank you, Kevin! As you suggested, I looked into ownerships/security issues and that turned out to be the problem. When I copied the contents to a new MS Word document that I made, and added the password myself, it worked as expected. – Xander Apr 19 '15 at 17:52