Encrypt PDFs with AES on Android

The AesDataProvider we ship with our Catalog example app allows you to efficiently read and write encrypted PDF documents in your app. The data format expected by the data provider is structured like this:

Byte:     | 0-15 |     16 - n    |
Contents: |  IV  | Encrypted PDF |

In the above table, the first 16 bytes contain the Initialization Vector (IV), while the AES256-CTR encrypted PDF starts at byte offset 16.

How to Encrypt Files

Using openssl, you can easily encrypt PDF files so that they can be used by the AesDataProvider.

  1. You need a key to encrypt your files with. For example, you can use the following values.

  • Hex: 110425c3748d6c1c1bc644a2d63c3089be01e17a9eb0254366ff4b7edb261355

  • Base64: EQQlw3SNbBwbxkSi1jwwib4B4XqesCVDZv9LftsmE1U=

  1. For every file you encrypt, you need to choose a new IV. This is used to make sure that encrypting the same file with the same key multiple times doesn’t result in the same encrypted file. We’ll use the following.

  • Hex: 97dad56befad54731ea696d2fd39a6d3

  • Base64: l9rVa++tVHMeppbS/Tmm0w==

  1. Start by writing the IV to your output file:

openssl enc -base64 -d <<< l9rVa++tVHMeppbS/Tmm0w== >> encrypted.pdf
  1. Then append the encrypted document to your output file:

openssl enc -aes-256-ctr -iv 97DAD56BEFAD54731EA696D2FD39A6D3 -K 110425c3748d6c1c1bc644a2d63c3089be01e17a9eb0254366ff4b7edb261355 -in source.pdf >> encrypted.pdf