pyauth / python-pkcs11

PKCS#11/Cryptoki support for Python
MIT License
149 stars 71 forks source link

Not possible to sign on PDF Signature field #108

Open ilpadrinohack opened 3 years ago

ilpadrinohack commented 3 years ago

Well, this is not an issue as a question. Is it possible to sign (visible signature) a PDF document on a signature field that I have created previously?

I am using this code to get my X.509 certificate from my spanish eID card, but also I don't know how to use this certificate to sign:

    from pkcs11 import Attribute, ObjectClass, NoSuchKey, SignMixin,KeyType
    import PyKCS11
    import OpenSSL

               lib = pkcs11.lib("/usr/lib64/pkcs11/opensc-pkcs11.so")
               fname='lorem_ipsum_definicion.pdf'
               data=open('lorem_ipsum_definicion.pdf', 'rb+').read()
               for slot in lib.get_slots():
                     token = slot.get_token()
                     print(token)

    with token.open(user_pin=<PIN>) as session:
        private = next(session.get_objects({Attribute.CLASS: ObjectClass.PRIVATE_KEY,}))
        public = next(session.get_objects({Attribute.CLASS: ObjectClass.PUBLIC_KEY,}))
        cert=next(session.get_objects({Attribute.CLASS: ObjectClass.CERTIFICATE,Attribute.LABEL:'CertFirmaDigital'}))
        sig = SignMixin.sign(data)
        print(sig)
        sig_verif = public.verify(data, sig) # Works!
        print("Signature is valid? "+str(sig_verif)) # True
        fname = fname.replace('.pdf', '-signed.pdf')
        with open(fname, 'wb') as fp:
             fp.write(data)
             fp.write(sig)

Any help will be grateful Thanks in advance

danni commented 3 years ago

Hi, this doesn't make a lot of sense. PKCS#11 has nothing to do with graphic signatures. It is to do with cryptographic signatures. Representing that value is beyond the scope of this library. Similarly, signing or encrypting PDFs via the Adobe extensions for signed PDFs is beyond the scope of this library. However this library could produce the signature required.

It would help to start from one of the examples of the tests. The exact mechanism, format and parameters of your signature need to match with the party you're changing it with.

You can't just call methods on SignMixin. You need to call it on an instance. To sign something you need a private key. Certificates, which contain the public keys, can only be used to verify a signature. Think of a certificate as a public key with attached metadata about its validity.