# Password protect a PDF in C#

> Encrypt a PDF with AES-256 in .NET, with a user password, an owner password and permissions such as print and copy. MIT licensed, pure C#.

Available since 1.0.

Encrypt a PDF so it needs a password to open, and limit what readers may do with it.

## Short answer

Call `doc.Security.Encrypt` with a user password, an owner password and the permissions to grant,
then save. The user password opens the file with those permissions; the owner password gives full
access. New protection is AES-256 unless you pass `PdfEncryption.Aes128`.

```csharp title="recipe-password-protect-pdf.cs"
#:package PdfNetStack@1.2.0
using PdfNetStack;

PdfDocument doc = PdfDocument.Open("report.pdf");
doc.Security.Encrypt(
    userPassword: "open-me",                     // needed to open the file
    ownerPassword: "owner-secret",               // needed to change it
    permissions: PdfPermissions.Print | PdfPermissions.CopyContent);   // AES-256 by default
doc.Save("report-protected.pdf");

PdfDocument check = PdfDocument.Open("report-protected.pdf", password: "open-me");
Console.WriteLine($"Opened with the user password: {check.Pages.Count} pages, {check.Security.Permissions}");
```

```bash
dotnet add package PdfNetStack
```

## Notes

Permissions are `Print`, `PrintHighQuality`, `Modify`, `CopyContent`, `Annotate`, `FillForms`,
`ExtractForAccessibility` and `Assemble`, combined with `|`. A document opened with only the user
password can be read but not saved. One opened with the owner password keeps its passwords and
permissions when saved.

## Related

- [Encryption](https://www.jadev-corp.com/guides/encryption/)
- [Remove a password from a PDF](https://www.jadev-corp.com/recipes/remove-pdf-password/)
- [Command line](https://www.jadev-corp.com/cli/): `pdfnetstack encrypt in.pdf out.pdf --user-password u --owner-password o --allow print,copy`
- API: [PdfSecurity](https://www.jadev-corp.com/api/pdfnetstack/pdfsecurity/), [PdfPermissions](https://www.jadev-corp.com/api/pdfnetstack/pdfpermissions/)

Source: https://www.jadev-corp.com/pdfnetstack/recipes/password-protect-pdf/
