iTextSharp 對PDF簽名

47 篇文章 0 订阅
12 篇文章 1 订阅

http://hi.baidu.com/xyesterday/item/d3897512363f9aff9c778aec


在本文提供的代码中,我寫了一个叫做PDFSigner的库,它是一个使用iTextSharp的工具包,实现了您进行数字签名所需要的一切。
它包括三个类:
Cert类:这个类用来封装证书,提取签名所需的信息,这个类中最重要的方法是:processCert()
MetaData类:元数据封装类
PDFSigner类:这个类的构造,需要一个证书对象,和一个元数据对象,最重要的方法是sign方法

processCert()方法:

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();

}

这个方法取证书,遍历它的所有元素,找到私钥提取出来。如果可能的话,它也创建证书链。


Sign()方法:

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();

}

这个函数讀取源PDF文档的内容,然后使用讀取的数据通过PDFStamper创建新的PDF。
PDFStamper是一个PDF书寫器,可以签名PDF文档。签名的外观可以定制,所以您可以为签名添加签名原因,联系方式,地址等属性。
SetCrypto方法允许我们使用从证书文件中提取出的私钥和链证书签名文档。
最后,如果需要添加一个可视外观的话,可以使用SetVisibleSignature方法。
PDFReader,PDFStamper和PdfSignatureAppearance由iTextSharp库提供。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值