File: encryption-decryption.md

package info (click to toggle)
pypdf 5.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 17,484 kB
  • sloc: python: 39,672; makefile: 35
file content (59 lines) | stat: -rw-r--r-- 1,704 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Encryption and Decryption of PDFs

PDF encryption makes use of [`RC4`](https://en.wikipedia.org/wiki/RC4) and
[`AES`](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) algorithms
with different key length. `pypdf` supports all of them until `PDF-2.0`, which
is the latest PDF standard.

`pypdf` use an extra dependency to do encryption or decryption for `AES` algorithms.
We recommend [`pyca/cryptography`](https://cryptography.io/en/latest/). Alternatively,
you can use [`pycryptodome`](https://pypi.org/project/pycryptodome/).

```{note}
Please see the note in the [installation guide](installation.md)
for installing the extra dependencies if interacting with PDFs that use AES.
```

## Encrypt

You can encrypt a PDF by using a password:

```python
from pypdf import PdfReader, PdfWriter

reader = PdfReader("example.pdf")
writer = PdfWriter(clone_from=reader)

# Add a password to the new PDF
writer.encrypt("my-secret-password", algorithm="AES-256")

# Save the new PDF to a file
with open("encrypted-pdf.pdf", "wb") as f:
    writer.write(f)
```
The algorithm can be one of `RC4-40`, `RC4-128`, `AES-128`, `AES-256-R5`, `AES-256`.
We recommend using `AES-256-R5`.

```{warning}
pypdf uses `RC4` by default for compatibility if you omit the "algorithm" parameter.
Since `RC4` is insecure, you should use `AES` algorithms.
```

## Decrypt

You can decrypt a PDF using the appropriate password:

```python
from pypdf import PdfReader, PdfWriter

reader = PdfReader("encrypted-pdf.pdf")

if reader.is_encrypted:
    reader.decrypt("my-secret-password")

writer = PdfWriter(clone_from=reader)

# Save the new PDF to a file
with open("decrypted-pdf.pdf", "wb") as f:
    writer.write(f)
```