Encrypt and Decrypt PDF Files in Java

Aspose.PDF for Java exposes PDF security operations through the PdfFileSecurity facade.

Encrypt a PDF with user and owner passwords

  1. Create and bind the PdfFileSecurity facade to the source PDF document.
  2. Configure the DocumentPrivilege and KeySize properties required by the example.
  3. Save the updated PDF document through PdfFileSecurity.
public static void encryptPdfWithUserOwnerPassword(Path inputFile, Path outputFile) {
    PdfFileSecurity fileSecurity = new PdfFileSecurity();
    fileSecurity.bindPdf(inputFile.toString());
    DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
    privilege.setAllowPrint(true);
    fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x128);
    fileSecurity.save(outputFile.toString());
    fileSecurity.close();
}

Encrypt a PDF with a specific algorithm

encryptPdfWithEncryptionAlgorithm uses KeySize.x256 together with Algorithm.AES to apply stronger encryption settings.

Decrypt a protected PDF

  1. Create and bind the PdfFileSecurity facade to the source PDF document.
  2. Decrypt the protected document with the owner password.
  3. Save the updated PDF document through PdfFileSecurity.
public static void decryptPdfWithOwnerPassword(Path inputFile, Path outputFile) {
    PdfFileSecurity fileSecurity = new PdfFileSecurity();
    fileSecurity.bindPdf(inputFile.toString());
    fileSecurity.decryptFile("owner_password");
    fileSecurity.save(outputFile.toString());
    fileSecurity.close();
}

The example set also includes tryDecryptPdfWithoutException, which returns false instead of throwing when decryption fails.

Change passwords and reset security

The PdfFileSecurityExamples class demonstrates:

  • changeUserAndOwnerPassword to replace both passwords.
  • changePasswordAndResetSecurity to change passwords and reapply privileges in one step.
  • tryChangePasswordWithoutException for a non-throwing password-change flow.

Set document privileges

To restrict actions such as printing and copying:

  1. Create and bind the PdfFileSecurity facade to the source PDF document.
  2. Set the required DocumentPrivilege permissions or encryption options.
  3. Set the properties required by the example.
  4. Save the updated PDF document through PdfFileSecurity.
public static void setPdfPrivilegesWithPasswords(Path inputFile, Path outputFile) {
    PdfFileSecurity fileSecurity = new PdfFileSecurity();
    fileSecurity.bindPdf(inputFile.toString());
    DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
    privilege.setAllowPrint(true);
    privilege.setAllowCopy(false);
    fileSecurity.setPrivilege("user_password", "owner_password", privilege);
    fileSecurity.save(outputFile.toString());
    fileSecurity.close();
}