Password Protect PDF using Python | Encrypt PDF using Python

We often use PDF files for data sharing but the information shared in PDF files may get compromised. So the PDF encryption is a viable solution and entities with sensitive information specifically use encryption techniques. Especially, banks, medical diagnostics, businesses, and government agencies commonly use encrypted PDFs. Once the file has been encrypted, the protection of the original work and trustworthiness of work ethics is established. In this article, we are going to discuss the details on how to encrypt PDF using Python.

REST API for PDF Processing

We have developed a REST-based API named Aspose.PDF Cloud which enables you to create, manipulate and convert PDF file formats to XLSX, PPTX, DOCX, MobiXML, HTML, and other supported document formats. Now in order to avail these features in Python application, we need to use Aspose.PDF Cloud SDK for Python which is a wrapper around REST API.

To get started using the free Python SDK, the first step is its installation. The SDK is available for download over PIP and GitHub repository. Now execute the following command on the terminal/command prompt to install the latest version of SDK on the system.

 pip install asposepdfcloud

Aspose.Cloud Dashboard

After the installation, the next major step is a free subscription to our cloud services via Aspose.Cloud dashboard. The purpose of this subscription is to only allow authorized persons to access our file processing services. If you have GitHub or Google account, simply Sign Up or, click on the Create a new Account button and provide the required information. Now login to the dashboard using credentials and expand the Applications section from the dashboard and scroll down towards the Client Credentials section to see Client ID and Client Secret details.

Client Credentials
Image 2:- Client credentials on Aspose.Cloud dashboard.

Encrypt PDF using Python

The API enables you to set two types of passwords i.e. Document open password (user password) and Permission password (owner password).

Document open password

Document Open password (also known as a user password) requires a user to type a password to open the PDF.

Permissions password

A permissions password (also known as a master/owner password) is required to change permission settings. Using a permissions password, you can restrict printing, editing, and copying content in the PDF. This password is required to change the restrictions you have already applied.

If the PDF is secured with both types of passwords, it can be opened with either password.

Also please note that the API accepts the owner and user passwords in Base64encoded format. In the following code snippet, the ownerPassword (b3duZXJcLy8/ICQxMl5QYXNzd29yZCEm) and userPassword (dXNlciAkXlBhc3N3b3JkISY=) are specified. Please follow the steps given below to encrypt PDF files using Python code snippet.

  • First, we need to create an instance of ApiClient class while providing Client ID and Client Secret as arguments
  • Secondly, create an instance of PdfApi class which takes ApiClient object as input argument
  • Now call the method post_encrypt_document_in_storage(..) method of PdfApi class while passing name of input PDF file, user and owner passwords in Base64 encoding and Cryptographic algorithm.
def encrypt():
    try:
        #Client credentials
        client_secret = "d34641f4ff6bcc96e3a0ab6ac69768b2"
        client_id = "8e2b082f-1f74-4bc0-b454-5f68457d1c97"

        #initialize PdfApi client instance using client credetials
        pdf_api_client = asposepdfcloud.api_client.ApiClient(client_secret, client_id)

        # create PdfApi instance while passing PdfApiClient as argument
        pdf_api = PdfApi(pdf_api_client)

        #input PDF file name
        input_file = 'image-based-pdf-sample.pdf'

        # call the API to encrypt the document
        response = pdf_api.post_encrypt_document_in_storage(name=input_file,user_password='dXNlciAkXlBhc3N3b3JkISY=',owner_password='b3duZXJcLy8/ICQxMl5QYXNzd29yZCEm',crypto_algorithm='AESX128')

        # print success message in console (optional)
        print('PDF encrypted successfully !')    
    except ApiException as e:
        print("Exception while calling PdfApi: {0}".format(e))
        print("Code:" + str(e.code))
        print("Message:" + e.message)

Please note that you can use either of the cryptographic algorithm value during the PDF encryption process

NameDescription
RC4x40RC4 with key length 40.
RC4x128RC4 with key length 128.
AESx128AES with key length 128.
AESx256AES with key length 256.

The input PDF file used in the above example can be downloaded from awesomeTable.pdf.

Encrypt PDF using cURL Command

The REST APIs are also accessible via cURL commands on any platform. We can use the command prompt/terminal window to execute the cURL commands. Since Aspose.PDF Cloud is also developed as per REST architecture, so we can also use the cURL command for encrypting the PDF files. But before proceeding further, we need to generate a JSON Web Token (JWT) based on your individual client credentials specified over Aspose.Cloud dashboard. It is mandatory because our APIs are only accessible to registered users. Please execute the following command to generate the JWT token.

curl -v "https://api.aspose.cloud/connect/token" \
-X POST \
-d "grant_type=client_credentials&client_id=bbf94a2c-6d7e-4020-b4d2-b9809741374e&client_secret=1c9379bb7d701c26cc87e741a29987bb" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json"

Now once we have the JWT token, we need to execute the following command to encrypt the PDF document.

curl -v -X POST "https://api.aspose.cloud/v3.0/pdf/awesomeTable.pdf/encrypt?userPassword=dXNlciAkXlBhc3N3b3JkISY%3D&ownerPassword=b3duZXJcLy8%2FICQxMl5QYXNzd29yZCEm&cryptoAlgorithm=AESx128&permissionsFlags=AssembleDocument&usePdf20=false" \
-H  "accept: application/json" \
-H  "authorization: Bearer <JWT Token>"

Conclusion

In this article, we have discussed the steps for encrypting the PDF document using Python code snippet and the cURL command. Please note that our cloud SDKs are built under an MIT license, so you may download the complete code snippet from GitHub and update it as per your requirements. We highly recommend you to explore the Developer Guide to learn more about other exciting features currently being offered by Cloud API.

In case you have any related queries or you encounter any issues while using our APIs, please feel free to contact us via the free customer support forum.

Related Articles

We also suggest going through the following articles to learn more about