Encrypt or Decrypt PDF in Python

PDFs, and other digital documents as well, are always prone to be tampered with by malicious actors. Therefore, the PDF files are encoded and encrypted before they are shared. The encrypted PDF files prevent unauthorized access and tampering of the content by malicious users. To perform PDF encryption programmatically, this article shows how to encrypt a PDF file in Python. Also, you will learn how to decrypt an encrypted PDF file in Python.

Python Library to Encrypt and Decrypt PDF

To encrypt and decrypt PDF files, we will use Aspose.PDF for Python. It is a powerful library that provides basic as well as advanced features to create and manipulate PDF files. Let’s first install the library using the following pip command.

pip install aspose-pdf

Encrypt a PDF in Python

Aspose.PDF for Python lets you encrypt the PDF files using AESx128, AESx256, RC4x40, and RC4x128 algorithms. You can choose one of these encryption algorithms and protect your PDF file with a password. The following are the steps to encrypt a PDF in Python.

  • First, use Document class to load the input PDF file using its path.
  • Then, use Document.encrypt(“user_password”, “owner_password”, DocumentPrivilege, CryptoAlgorithm, bool) method to encrypt PDF.
  • Finally, save the encrypted PDF using Document.save() method.

The following code sample shows how to encrypt and password-protect a PDF in Python.

Decrypt a PDF in Python

You can also decrypt an encrypted PDF file using Aspose.PDF for Python. For this, you need to know the password of the protected PDF. The following are the steps to decrypt an encrypted PDF.

  • First, create an instance of Document class and initialize it with PDF’s path and password.
  • Then, call Document.decrypt() method to decrypt the PDF.
  • Finally, save the decrypted PDF using Document.save() method.

The below code sample demonstrates how to decrypt a PDF file in Python.

Protect PDF Files Online

We also provide a free online tool to password-protect PDF files. You can use this tool to protect your PDF files without creating an account.

Get a Free License

You can get a free temporary license and evaluate the PDF encryption feature without any limitations.

Explore Python PDF Library

You can learn more about our Python PDF library using the documentation. Explore its amazing features and share your suggestions, questions, or queries with us via our forum.

Conclusion

In this article, you have learned how to encrypt PDF files in Python. In addition, you have seen how to decrypt the encrypted PDF files from within your Python applications. In the end, we provided you with our web-based tool to protect PDF files online and for free.

See Also