Protection and encryption with PHP

Protection and encryption of Word documents with PHP

Introduction to Cryptophpdocx

Cryptophpdocx is a new functionality added to the Premium version of phpdocx that has been designed to deal with the protection and encryption of Word documents.

Cryptophpdocx implements the required cryptographic methods defined by Microsoft in its MS-Crypto standard for password hashing and encryption of OOXML documents.


  • That a Word document is password protected does not ensure that it can not be modified by a third party with some knowledge of the OOXML standard.
  • Password protection should be understood as a mean to avoid unintentionally changes on certain parts of a Word document.
  • Anyhow, it is not posible, unless the password is known, to modify and re-protect the same document, so modifications may be easily detected.
  • If no password protection is needed one may use the phpdocx method markAsFinal to indicate the user that the document is not supposed to be changed.
Document protection

To protect a Word document with Cryptophpdocx is extremely simple:

A few comments are due at this point:

  • If no "type" in the options array the read only property is applied. The available types are:
    • readOnly: the user may not do any change on the document unless (s)he introduces the password.
    • comments: the user may only freely change comments, any other change requires to introduce the pass
    • forms: the user may only fulfill the forms available on the document, any other chage requires to introduce the password.
    • trackedChanges: the change tracking can not be desactivated without introducing the password.
  • One may use the overwrite option to change the password in documents that have already been protected previously by PHPDocX or otherwise.

You may equally password protect a PDF document with a few lines of code:

The passwordOwner parameter is optional and if set it allows the final user to get full access to the PDF as long as (s)he knows the password.

The full lists of permissions that may be blocked include: print, modify, copy, annot-forms, fill-forms, extract, assemble, print-high.

Document encryption

The goal of encrypting a Word document is to avoid that unauthorized users are abble to access the contents of the file.

In order to open an encrypted Word document the user must introduce the correct password beforehand.

Word documents encrypted with the Word interface, even if preserving the docx extension, are outside the scope of the OOXML standard and use the Binary Compound File standard of Microsoft (although after decryption they are converted to standard Word documents).

The code to encrypt a docx is as simple as this:

Whenever the user tries to open the Word document (s)he will be prompted to introduce the password to be able to read the document.

The case of PDF encryption requires a similar chunk of code: