利用iTextSharp对PDF进行签名(E-signing PDF documents with iTextSharp)--推荐

在CodeProject上看到一篇不错的文章,所以在这里还是向大家推荐一下。
http://files.cnblogs.com/hardrock/Esignature_src.zip 

Introduction

In this article I will present a simple source code allowing you to digitally sign a PDF document and modify its Meta data. 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 are digital signatures or how does 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 demo certificate from here.
Then extract the pkcs#12 certificate as described bellow :

  • Open Internet explorer and click on tools then internet options
  • Go to 'content' tab and click 'certificats'
  • Choose a certificate from the list and click Export
  • Follow the wizard and when asked choos to include private key with extracted certificate
  • Enter a password when prompted (dont 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
5 – add signature information if needed (reason, contact and location)
6 – click sign button
In the debug box you’ll see operaion’s progress
If everything goes well open your explorer and browse to location you entered for Target file, open this file with Adobe Acrobat reader, your document is signed! =)

Now how all this work?

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

  • Cert class: this class is used to hold a certificate and extract needed information for signature, the most important methode in this class is processCert (will be explained bellow)
  • MetaData class : holds PDF meta data
  • PDFSigner class : the construction of this class takes a Cert object and if needed a MetaData object, the most important methode here is the sign methode (will be explained bellow)

    processCet method

     
        
    None.gif          private   void  processCert()
    ExpandedBlockStart.gifContractedBlock.gif        
    dot.gif {
    InBlock.gif                
    string alias = null;                                                
    InBlock.gif                PKCS12Store pk12;
    InBlock.gif
    InBlock.gif                
    //First we'll read the certificate file
    InBlock.gif
                    pk12 = new PKCS12Store(new FileStream(this.Path, FileMode.Open, FileAccess.Read), this.password.ToCharArray());
    InBlock.gif
    InBlock.gif                
    //then Iterate throught certificate entries to find the private key entry
    InBlock.gif
                    IEnumerator i = pk12.aliases();
    InBlock.gif                
    while (i.MoveNext())
    ExpandedSubBlockStart.gifContractedSubBlock.gif                
    dot.gif{
    InBlock.gif                    alias 
    = ((string)i.Current);
    InBlock.gif                    
    if (pk12.isKeyEntry(alias))
    InBlock.gif                        
    break;
    ExpandedSubBlockEnd.gif                }

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

    None.gif
    This methode reads the certificate and iterate throught its entries to find the private key entry then extract it.
    it also construct the certificate's chain if available

    sign method

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

    InBlock.gif    st.MoreInfo 
    = this.metadata.getMetaData();
    InBlock.gif    st.XmpMetadata 
    = this.metadata.getStreamedMetaData();
    InBlock.gif    PdfSignatureAppearance sap 
    = st.SignatureAppearance;
    InBlock.gif    
    InBlock.gif    sap.SetCrypto(
    this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    InBlock.gif    sap.Reason 
    = SigReason;
    InBlock.gif    sap.Contact 
    = SigContact;
    InBlock.gif    sap.Location 
    = SigLocation;            
    InBlock.gif    
    if (visible)
    InBlock.gif        sap.SetVisibleSignature(
    new iTextSharp.text.Rectangle(100100250150), 1null);
    InBlock.gif    
    InBlock.gif    st.Close();
    ExpandedBlockEnd.gif}
    this function reads the content of a given pdf , then it use the read data to create a new PDF using PDFStamper.
    PDFStamper is a PDF Writer that can sign PDF documents, the signature appearence can be configured so you can add a reason, a contact and a location attributes to the signature.
    SetCrypto methode allows us to sign the document using the private key and chain certificate we extracted from the certificate file.
    And finally, the SetVisibleSignature is used if you need to add a visible signature to the document

    PDFReader, PDFStamper and PdfSignatureAppearance are provided by iTextSharp library

     From http://www.codeproject.com/useritems/Esignature.asp
 
 
本文转自 RubyPdf 的中文博客博客园博客,原文链接: http://www.cnblogs.com/hardrock/archive/2006/06/28/438163.html,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值