Skip to content
Advertisement

Python Encrypt PDF Simple Method AES 256

I have used this method to encrypt a PDF file with AES 128:

import PyPDF2
pdffile = open(r"input.pdf", "rb")
pdfReader = PyPDF2.PdfFileReader(pdffile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
    pdfWriter.addPage(pdfReader.getPage(pageNum))

pdfWriter.encrypt('password')
resultPDF = open(r"output.pdf", "wb")
pdfWriter.write(resultPDF)
resultPDF.close()

…but is there a similarly-simple way to use AES 256?

Thanks in advance!

Advertisement

Answer

I have the same issue. I use pikepdf to solve it.

import pikepdf
with pikepdf.Pdf.open(r"input.pdf") as pdf:
    pdf.save(r"output.pdf", encryption=pikepdf.Encryption(
        owner='password', user='password'))

By default, pikepdf use AES-256 to encrypt.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement