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, OpenOptions};

fn main() -> pdfluent::Result<()> {
    let mut doc = PdfDocument::open_with(
        "locked.pdf",
        OpenOptions::new().with_password("s3cret"),
    )?;
    doc.decrypt("s3cret")?;
    doc.save("decrypted.pdf")?;
    Ok(())
}

Step by step

1

Open the encrypted PDF

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

rust
use pdfluent::{PdfDocument, OpenOptions};

let mut doc = PdfDocument::open_with("protected.pdf", OpenOptions::new().with_password("open123"))?;
2

Handle a wrong password

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

rust
use pdfluent::{PdfDocument, OpenOptions};

let result = PdfDocument::open_with("protected.pdf", OpenOptions::new().with_password("guess"));
match result {
    Ok(doc) => { /* proceed */ }
    Err(_) => eprintln!("Could not open - wrong or missing password."),
}
3

Check the encryption details

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

rust
// Strip the encryption so the saved copy opens without a password
doc.decrypt("open123")?;
4

Remove encryption

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

rust
doc.save("decrypted.pdf")?;
5

Save the unprotected document

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

rust
// Verify by re-opening without a password
let check = PdfDocument::open("decrypted.pdf")?;
println!("Re-opened without a password: {} pages", check.page_count());

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_with(), 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_with() 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