Encrypt and Decrypt PDF Files in Java
Contents
[
Hide
]
Aspose.PDF for Java exposes PDF security operations through the PdfFileSecurity facade.
Encrypt a PDF with user and owner passwords
- Create and bind the PdfFileSecurity facade to the source PDF document.
- Configure the DocumentPrivilege and KeySize properties required by the example.
- 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
- Create and bind the PdfFileSecurity facade to the source PDF document.
- Decrypt the protected document with the owner password.
- 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:
changeUserAndOwnerPasswordto replace both passwords.changePasswordAndResetSecurityto change passwords and reapply privileges in one step.tryChangePasswordWithoutExceptionfor a non-throwing password-change flow.
Set document privileges
To restrict actions such as printing and copying:
- Create and bind the PdfFileSecurity facade to the source PDF document.
- Set the required DocumentPrivilege permissions or encryption options.
- Set the properties required by the example.
- 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();
}