Protection and encryption with PHP

Protection and encryption of Word, Excel, PowerPoint and PDF 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.

Document protection

To protect a Word document with Cryptophpdocx is extremely simple:

A few comments are due at this point:

  • If there's 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 enter 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 deactivated without typing 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 MS office document is to avoid that unauthorized users are able to access the contents of the file.

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

MS Office 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 enter the password to be able to read the document.

XLSX and PPTX documents can also be encrypted:

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