title: Digitally Sign and Verify Pdf Document using itextSharp 5.3.3
body: <p>I am trying to digitally sign and Verify pdf documents on server(c#) using iTextSharp 5.3.3.</p>
  
  <p>I have generated .Pfx file using DigiSign(Online tool) and then using windows to generate the certificate(.cer) file</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Signs a PDF document using iTextSharp library
  /// &lt;/summary&gt;
  /// &lt;param name="sourceDocument"&gt;The path of the source pdf document which is to be signed&lt;/param&gt;
  /// &lt;param name="destinationPath"&gt;The path at which the signed pdf document should be generated&lt;/param&gt;
  /// &lt;param name="privateKeyStream"&gt;A Stream containing the private/public key in .pfx format which would be used to sign the document&lt;/param&gt;
  /// &lt;param name="keyPassword"&gt;The password for the private key&lt;/param&gt;
  /// &lt;param name="reason"&gt;String describing the reason for signing, would be embedded as part of the signature&lt;/param&gt;
  /// &lt;param name="location"&gt;Location where the document was signed, would be embedded as part of the signature&lt;/param&gt;    
  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();
              }
          }
      }
  </code></pre>
  
  <p>Once the document is signed, i need to verify the document. I use below code, but get errors.</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Verifies the signature of a prevously signed PDF document using the specified public key
  /// &lt;/summary&gt;
  /// &lt;param name="pdfFile"&gt;a Previously signed pdf document&lt;/param&gt;
  /// &lt;param name="publicKeyStream"&gt;Public key to be used to verify the signature in .cer format&lt;/param&gt;
  /// &lt;exception cref="System.InvalidOperationException"&gt;Throw System.InvalidOperationException if the document is not signed or the signature could not be verified&lt;/exception&gt;
  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&lt;VerificationException&gt;[] 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.");
          }
      }
  }
  </code></pre>
  
  <p>I get two errors in verifying:</p>
  
  <ol>
  <li>One at (!pk.VerifyTimestampImprint()) --> The signature timestamp could not be verified.</li>
  <li>Another one at CertificateVerification.VerifyCertificates --> NullReference Error</li>
  </ol>
  
  <p>Appreciate any help in this regard.</p>