3

I am trying to digitally sign and Verify pdf documents on server(c#) using iTextSharp 5.3.3.

I have generated .Pfx file using DigiSign(Online tool) and then using windows to generate the certificate(.cer) file

/// <summary>
/// Signs a PDF document using iTextSharp library
/// </summary>
/// <param name="sourceDocument">The path of the source pdf document which is to be signed</param>
/// <param name="destinationPath">The path at which the signed pdf document should be generated</param>
/// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param>
/// <param name="keyPassword">The password for the private key</param>
/// <param name="reason">String describing the reason for signing, would be embedded as part of the signature</param>
/// <param name="location">Location where the document was signed, would be embedded as part of the signature</param>    
public static void signPdfFile (string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location)
    {
        Pkcs12Store pk12=new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());
        privateKeyStream.Dispose();

        //then Iterate throught certificate entries to find the private key entry
        string alias=null;
        foreach (string tAlias in pk12.Aliases)
        {
            if (pk12.IsKeyEntry(tAlias))
            {
                alias = tAlias;
                break;
            }
        }
        var pk=pk12.GetKey(alias).Key;

        // reader and stamper
        PdfReader reader = new PdfReader(sourceDocument);
        using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite))
        {
            using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
            {
                // appearance
                PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                //appearance.Image = new iTextSharp.text.pdf.PdfImage();
                appearance.Reason = reason;
                appearance.Location = location;
                appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), 1, "Icsi-Vendor");
                // digital signature
                IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
                MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

                stamper.Close();
            }
        }
    }

Once the document is signed, i need to verify the document. I use below code, but get errors.

/// <summary>
/// Verifies the signature of a prevously signed PDF document using the specified public key
/// </summary>
/// <param name="pdfFile">a Previously signed pdf document</param>
/// <param name="publicKeyStream">Public key to be used to verify the signature in .cer format</param>
/// <exception cref="System.InvalidOperationException">Throw System.InvalidOperationException if the document is not signed or the signature could not be verified</exception>
public static void verifyPdfSignature (string pdfFile, Stream publicKeyStream)
{
    var parser=new X509CertificateParser();
    var certificate=parser.ReadCertificate(publicKeyStream);
    publicKeyStream.Dispose();

    PdfReader reader = new PdfReader(pdfFile);
    AcroFields af = reader.AcroFields;
    var names = af.GetSignatureNames();

    if (names.Count == 0)
    {
        throw new InvalidOperationException("No Signature present in pdf file.");
    }

    foreach (string name in names)
    {
        if (!af.SignatureCoversWholeDocument(name))
        {
            throw new InvalidOperationException(string.Format("The signature: {0} does not covers the whole document.", name));
        }

        PdfPKCS7 pk = af.VerifySignature(name);
        var cal = pk.SignDate;
        var pkc = pk.Certificates;

        if (!pk.Verify())
        {
            throw new InvalidOperationException("The signature could not be verified.");
        }
        if (!pk.VerifyTimestampImprint())
        {
            throw new InvalidOperationException("The signature timestamp could not be verified.");
        }

        IList<VerificationException>[] fails = CertificateVerification.VerifyCertificates(pkc, new X509Certificate[] { certificate }, null, cal);
        if (fails != null)
        {
            throw new InvalidOperationException("The file is not signed using the specified key-pair.");
        }
    }
}

I get two errors in verifying:

  1. One at (!pk.VerifyTimestampImprint()) --> The signature timestamp could not be verified.
  2. Another one at CertificateVerification.VerifyCertificates --> NullReference Error

Appreciate any help in this regard.

bayyinah
  • 139
  • 1
  • 3
  • 12
  • 2
    As a side note: *iTextSharp 5.3.3* - what about updating to a current version, i.e. **5.5.x**? If I remember corrctly, the 5.3.x versions were the time of the big update of the iText signing API. Thus, you probably deal with long fixed glitches. – mkl Sep 30 '14 at 07:07
  • thankyou mkl..i have changed to 5.5.0 and is working fine.. – bayyinah Oct 02 '14 at 05:36
  • mkl..can u check this question. i don't find any info regarding this. http://stackoverflow.com/questions/26155099/extension-of-letters-kashida-arabic-in-pdf-using-itextsharp – bayyinah Oct 02 '14 at 07:56
  • *can u check this question* - I'm not into the details of non-Latin fonts in iText(Sharp) and, therefore, can give no definitive answer. As far as I know, though, there often were people asking for features concerning specialties of such fonts but hardly ever those people were prepared to pay for such a development or to help develop the feature. Thus, I doubt that feature you're looking for is currently implemented. – mkl Oct 02 '14 at 08:40
  • could you share website of DigiSign? I need to also create a pfx for the document signing. I need to access directly online service or any SDK to help me to create a pfx. It can be also a trial version. – unbalanced Dec 07 '16 at 12:18

0 Answers0