Click here to Skip to main content
Click here to Skip to main content

E-signing PDF documents with iTextSharp

By , 17 Jun 2006
 

Sample Image - Esignature.jpg

Introduction

In this article, I will present a simple source code allowing you to digitally sign a PDF document and modify its metadata. I will use the excellent and free port of iText library: iTextSharp that can be downloaded here. You'll need Visual Studio 2005 to be able to open and build the project.

If you don’t know what digital signatures are or how they work, you can go here or here, or simply ask Google :)

iTextSharp provides a lot of interesting features to create and manipulate PDF documents, but in this article, we will only use digital signature functions. I will also use some function to manipulate PKCS#12 certificates; the only thing you need to know here is that our digital signature will use a private key extracted from a PKCS#12 certificate.

Getting started

So the first thing you have to do is to install a certificate on your browser. If you don’t have one, you can install the demo certificate from here. Then, extract the PKCS#12 certificate as described below:

  • Open Internet Explorer and click on Tools, then Internet Options.
  • Go to the 'Content' tab and click 'Certificates'.
  • Choose a certificate from the list and click Export.
  • Follow the wizard, and when asked, choose to include private key with the extracted certificate.
  • Enter a password when prompted (don't give an empty one!!!)

You are now ready to use the code provided in this article. Using the signature example:

  1. Compile and run the example.
  2. Browse to the PDF source file you want to sign.
  3. Browse and choose a destination PDF file.
  4. Add/modify the PDF meta data if you want.
  5. Browse to the certificate (the .pfx file) you just extracted and choose it.
  6. Give the password you used to extract the certificate.
  7. Add signature information if needed (reason, contact, and location).
  8. Click the Sign button.

In the debug box, you’ll see the operation’s progress. If everything goes well, open your explorer and browse to the location you entered for the target file, open this file with Adobe Acrobat reader, and your document is signed! =).

Now, how will all this work?

In the source code provided with this article, I wrote a library called PDFSigner. It’s a helper package that uses iTextSharp and doed everything you need for digital signatures. It contains three classes:

  • Cert: this class is used to hold a certificate and extract the needed information for the signature; the most important method in this class is processCert (will be explained below).
  • MetaData: holds the PDF metadata.
  • PDFSigner: the construction of this class takes a Cert object and, if needed, a MetaData object. The most important method here is the Sign method (will be explained below).

processCet method

private void processCert()
{
    string alias = null;
    PKCS12Store pk12;

    //First we'll read the certificate file
    pk12 = new PKCS12Store(new FileStream(this.Path, FileMode.Open, 
                               FileAccess.Read), this.password.ToCharArray());

    //then Iterate throught certificate entries to find the private key entry
    IEnumerator i = pk12.aliases();
    while (i.MoveNext())
    {
        alias = ((string)i.Current);
        if (pk12.isKeyEntry(alias))
            break;
    }

    this.akp = pk12.getKey(alias).getKey();
    X509CertificateEntry[] ce = pk12.getCertificateChain(alias);
    this.chain = new org.bouncycastle.x509.X509Certificate[ce.Length];
    for (int k = 0; k < ce.Length; ++k)
        chain[k] = ce[k].getCertificate();
}

This method reads the certificate and iterates through its entries to find the private key entry, then extracts it. It also construct the certificate's chain if available.

Sign method

public void Sign(string SigReason, string SigContact, string SigLocation, bool visible)
{
    PdfReader reader = new PdfReader(this.inputPDF);
    //Activate MultiSignatures
    PdfStamper st = PdfStamper.CreateSignature(reader, 
       new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);
    //To disable Multi signatures uncomment this line :
    //     every new signature will invalidate older ones !
    //PdfStamper st = PdfStamper.CreateSignature(reader, 
      new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0'); 

    st.MoreInfo = this.metadata.getMetaData();
    st.XmpMetadata = this.metadata.getStreamedMetaData();
    PdfSignatureAppearance sap = st.SignatureAppearance;
    
    sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, 
                  PdfSignatureAppearance.WINCER_SIGNED);
    sap.Reason = SigReason;
    sap.Contact = SigContact;
    sap.Location = SigLocation;
    if (visible)
        sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
    
    st.Close();
}

This function reads the content of a given PDF, then it uses the read data to create a new PDF using PDFStamper. PDFStamper is a PDF Writer that can sign PDF documents. The signature appearance can be configured so you can add a reason, a contact, and a location attribute to the signature. The SetCrypto method allows us to sign the document using the private key and chain certificate we extracted from the certificate file. And finally, SetVisibleSignature is used if you need to add a visible signature to the document. PDFReader, PDFStamper and PdfSignatureAppearance are provided by the iTextSharp library.

Well, that’s all for now :) I hope that you found my first article useful … If you have any questions or have any problems to build/run this example, don’t hesitate to post a comment.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

About the Author

Alaa-eddine KADDOURI
Software Developer
France France
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionWhat to do when PKCS #12 cert is not available PinmemberHarvey Flaisher27 Mar '13 - 13:08 
Questionvb.net Pinmemberewerton.4722 Feb '13 - 4:35 
QuestionThank you PinmemberKalpana Volety11 Jan '13 - 11:38 
QuestionSignature not valid Pinmembersodakdoogie12 Dec '12 - 5:42 
QuestionFantasic piece of code Pinmemberzaxbowow12 Oct '12 - 6:36 
QuestionProtected pdf with Password Pinmemberanismanoula2 Oct '12 - 5:33 
QuestionProblem with certificates PinmemberMelechDavid5 Jul '12 - 5:33 
Questiongot NullReferenceException while trying sample code Pinmemberai_mueller10 Sep '11 - 12:10 
GeneralBut it does not hv an option to signa selected page PinmemberSujit Soni31 May '11 - 9:07 
GeneralCertificate Error PinmemberelBaz24 Mar '11 - 8:34 
GeneralNew version of itextsharp PinmemberChristatos2 Feb '11 - 22:40 
GeneralByte[] to File.pdf PinmemberMember 362262327 Oct '10 - 13:12 
GeneraliSafePDF v1.3.0 is out PinmemberAlaa-eddine KADDOURI3 Sep '10 - 2:44 
GeneralSigning with store certificate Pinmemberashishdhingra9 Aug '10 - 19:26 
Generalinvisible signature if cert is installed Pinmemberbbembi_de18 Jul '10 - 23:24 
GeneralNew article about digital signature PinmemberAlaa-eddine KADDOURI2 Jun '10 - 9:23 
GeneralNew version available PinmemberAlaa-eddine KADDOURI23 Apr '10 - 2:51 
GeneralOrg.BouncyCastle.Crypto.AsymmetricKeyParameter exist in itextsharp.dll Pinmemberta00729 Sep '09 - 19:20 
Generalsign pdf's using timestamps from verisign PinmemberMember 219135114 Sep '09 - 4:22 
Answerpk12.getCertificateChain(alias) == null problem Pinmemberantiacid26 Aug '09 - 5:05 
Questionwhat version of the iTextSharp.dll Pinmemberju168182 Jul '09 - 4:10 
GeneralWindows service Error [modified] PinmemberYekbunn25 Jun '09 - 0:11 
GeneralRegarding signing pdf with itextsharp PinmemberAnil Vijay Singh17 Jun '09 - 0:17 
GeneralUsing pkcs#11 to allow SmartCard auth Pinmembernarva10 Jun '09 - 21:28 
QuestionAny way to use HttpClientCertificate ? PinmemberJJC_7813 May '09 - 1:52 
Questionhow can I add a timestamp? Pinmemberjaviovi20036 May '09 - 5:54 
QuestionASP .NET Compatible? PinmemberJJC_7828 Apr '09 - 21:45 
QuestionSign Multiple Pages of PDF [modified] Pinmembershaqil11 Apr '09 - 1:21 
QuestionSignature position PinmemberDaniel Kamisnki7 Apr '09 - 6:00 
QuestionPDF/A compatible? Pinmemberperformis26 Mar '09 - 4:26 
GeneralExample in VB PinmemberUgoMontefiori16 Feb '09 - 3:11 
GeneralRequest: already compiled code ready to use PinmemberBilou_Gateux15 Feb '09 - 0:16 
QuestionExpiry Date of the certificate PinmemberSai19711 Feb '09 - 17:06 
QuestionHow to install Demo Certificate and implement Digital Signature PinmemberTechSasi22 Jan '09 - 19:23 
Questionvalidate the expiry of the certificate PinmemberSai197121 Jan '09 - 22:10 
GeneralMultisignature Pinmemberyunan15 Jan '09 - 16:03 
QuestionHow to get the correct Private Key Pinmembersbromanv11 Dec '08 - 15:32 
GeneralError trying to sign a document from a certificate stored in IE Pinmembergpincay21 Nov '08 - 5:34 
Generalcertificate error PinmemberJames A. Mew4 Nov '08 - 3:15 
Generaltime stamps a date and time after signature is applied Pinmemberrajpura2 May '08 - 19:42 
QuestionHow to select certiifcate from Windows Store? Pinmemberboatek11 Apr '08 - 3:32 
GeneralVery nice! PinmemberMember 294305831 Jan '08 - 21:21 
QuestionCertificate of windows PinmembervikthorAB21 Jan '08 - 1:27 15 
Generalcert from card reader Pinmembercheong17 Jan '08 - 15:44 
General.cert files [modified] Pinmemberoguvenis5 Dec '07 - 23:02 
GeneralTry this for ASP.NET Websites Pinmemberjay_dubal7 Nov '07 - 18:50 
Questionsmartcard reader Pinmembercheong24 Sep '07 - 18:34 
GeneralCert password Pinmembercheong20 Sep '07 - 23:25 
QuestionSupported Signature Certificates.. PinmemberNick Kowalewicz5 Sep '07 - 7:54 
GeneralSign Documents on Pocket PC Pinmembermillencobrasil25 May '07 - 7:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 17 Jun 2006
Article Copyright 2006 by Alaa-eddine KADDOURI
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid