Sign a PDF without private key with iText7

2.1k views Asked by At

I'm evaluating iText7 and does not manage to sign a pdf with a self signed certificate that has no private key.

I'm trying to do this :

        X509Store store = new X509Store(StoreLocation.CurrentUser);

        store.Open(OpenFlags.ReadOnly);
        var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyName", false);
        var refDate = DateTime.MinValue;
        X509Certificate2 certificate = certs[0];

        var pk = DotNetUtilities.GetKeyPair(certificate.PrivateKey).Private; //how to do without private key ????

        IExternalSignature pks = new PrivateKeySignature(pk, "SHA-256");
        var bCert = DotNetUtilities.FromX509Certificate(certificate);
        var chain = new Org.BouncyCastle.X509.X509Certificate[] {bCert};
        using (var reader = new PdfReader(@"D:\Test\ToSign.pdf"))
        using (var stream = new FileStream(@"D:\Test\Signed.pdf", FileMode.OpenOrCreate)) {
            PdfSigner signer = new PdfSigner(reader, stream, false);
            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
        }

I DO understand that I should use a private key to be able to be sure to identify who signed the PDF, but our current PDF Library which is a COM component manages to sign the pdf without any private key.

Can you tell me how to do the same ?

Regards

1

There are 1 answers

3
Lonzak On

As the others mentioned in the comments: When there is a public key there is always a private key (which you may not have).

But one possibility is that your COM component is using the public key for the signing process. In asymmetric encryption you could

  • encrypt with the private key and decrypt with the public key (called digital signing which is used for PDF signing) OR
  • you can encrypt with the public key and decrypt with the private key (called encryption which is used in PGP).

So maybe this component is using the public key (instead the private key) for signing, but as mentioned you are then not able to verify the document since in PDF signing (normaly) the public key is attached to the signature. If any PDF reader/library gets the document it will throw an error verifying the document.

To "emulate" that behaviour in iText you could take the public key from the certificate and convert it into a private key and use it for signing. However this doesn't make sense and would probably create corrupt PDF files which are not verifiable. So I advice against it...