How-to guides/Security & Encryption

Decrypt a password-protected PDF in Rust

Open an encrypted PDF with the user or owner password and save an unprotected copy. Works with RC4-128 and AES-128/256 encrypted files.

rust
use pdfluent::PdfDocument;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = PdfDocument::open_encrypted("protected.pdf", "open123")?;
    doc.remove_encryption()?;
    doc.save("unprotected.pdf")?;
    println!("Encryption removed.");
    Ok(())
}
Install:cargo add pdfluentDownload SDK →

Step by step

1

Open the encrypted PDF

Use PdfDocument::open_encrypted() and provide the user or owner password. The method returns an error if the password is wrong.

rust
use pdfluent::PdfDocument;

let mut doc = PdfDocument::open_encrypted("protected.pdf", "open123")?;
2

Handle a wrong password

Match on PdfError::WrongPassword to give the user a clear error instead of a generic failure.

rust
use pdfluent::{PdfDocument, PdfError};

let result = PdfDocument::open_encrypted("protected.pdf", "guess");
match result {
    Ok(doc) => { /* proceed */ }
    Err(PdfError::WrongPassword) => eprintln!("Wrong password."),
    Err(e) => return Err(e.into()),
}
3

Check the encryption details

After opening, inspect the encryption type and permission flags that were set by the document author.

rust
let enc = doc.encryption_info()?;
println!("Algorithm: {:?}", enc.algorithm);
println!("Print allowed: {}", enc.permissions.print_allowed);
println!("Copy allowed: {}", enc.permissions.copy_text_allowed);
4

Remove encryption

Call remove_encryption() to strip all password protection and permission flags from the document in memory.

rust
doc.remove_encryption()?;
5

Save the unprotected document

Save to a new path. The saved file will open in any PDF reader without a password.

rust
doc.save("unprotected.pdf")?;

Notes and tips

  • You can use the owner password to open the document even when the user password is different. The owner password grants full access regardless of permission flags.
  • After calling open_encrypted(), all normal PDFluent operations work on the document. You do not need to remove encryption to extract text or render pages.
  • Some PDFs are encrypted but have no user password. They open without a password in readers but still have permission flags. open_encrypted() with an empty string handles this case.

Why PDFluent for this

Pure Rust

No JVM, no runtime, no DLL dependencies. Ships as a single native binary or WASM module.

Memory safe

Rust's ownership model prevents buffer overflows and use-after-free. No segfaults in PDF parsing.

Runs anywhere

Same code runs server-side, in Docker, on AWS Lambda, on Cloudflare Workers, or in the browser via WASM.

Frequently asked questions