How to digitally sign PDF documents using Python with an etoken (pen drive)?

hsvvijay picture hsvvijay · Jul 12, 2017 · Viewed 14.3k times · Source

How to digitally sign PDF documents using Python? I have an etoken (in pen drive).

Additionally, I have created an excel file using openpyxl and converted it into PDF. Now there is a requirement that I need to add digital signature to that PDF document.

Is there any way I can achieve this in python?

Answer

Grzegorz Makarewicz picture Grzegorz Makarewicz · Sep 21, 2018

Use python module designed for this task, it signs digitally PDF-s. Everything what You should have is p12/pfx file with certificate.

Simple example in: github repository example

#!/usr/bin/env python3
# *-* coding: utf-8 *-*
from oscrypto import asymmetric
from endesive import pdf

def main():
    dct = {
        b'sigflags': 3,
        b'contact': b'[email protected]',
        b'location': b'City',
        b'signingdate': b'20180731082642+02\'00\'',
        b'reason': b'Some descriptive message',
    }
    p12 = asymmetric.load_pkcs12(
        open('demo2_user1.p12', 'rb').read(),
        '1234'
    )
    datau = open('pdf.pdf', 'rb').read()
    datas = pdf.cms.sign(datau, dct, p12[0], p12[1], [], 'sha256')
    with open('pdf-signed-cms.pdf', 'wb') as fp:
        fp.write(datau)
        fp.write(datas)

main()