title: Apply digital signature to PDF using iTextSharp PKCS#7
body: <p>I'm developing an windows application in which i need to sign digital signature to a PDF file for that I've used below code which is working good for .pfx and .p12 certificates.</p>
  <h1>Code</h1>
  <pre><code>using Org.BouncyCastle.Pkcs;
  using System.IO;
  using iTextSharp.text.pdf;
  using iTextSharp.text.pdf.security;
  
  public class DigitalSignaturePDF
  {
      public void DigiSignPdf(string sourceDocument,
          string destinationPath,
          Stream privateKeyStream,
          string keyPassword,
          string reason,
          string location,
          bool isVisibleSignature)
      {
          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.Append, FileAccess.Write))
          {
              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;
                  if (isVisibleSignature)
                  {
                      appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), reader.NumberOfPages, null);
                  }
                  // digital signature
                  IExternalSignature es = new PrivateKeySignature(pk, &quot;SHA-256&quot;);
                  MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);
  
                  stamper.Close();
              }
          }
          reader.Close();
          reader.Dispose();
      }
  }
  </code></pre>
  <p>Now i need to prepair same code for .p7b (pkcs#7) files, can any one have any idea about signing pdf files using pkcs#7 certificates.</p>