数字签名
使用 iTextSharp 进行自定义数字签名。
引言
在本文中,我将展示一段简单的源代码,允许您对 PDF 文档进行数字签名并修改其元数据。我将使用出色的免费端口 iText 库:iTextSharp,您可以从 这里 下载。您需要 Visual Studio 2008 才能打开和构建该项目。
如果您不了解数字签名是什么以及它们如何工作,您可以访问 这里 或 这里,或者直接向 Google 提问 :).
iTextSharp 提供了许多有趣的功能来创建和操作 PDF 文档,但在本文中,我们只会使用数字签名功能。我还会使用一些函数来操作 PKCS#12 证书。您只需要知道的是,我们的数字签名将使用从 PKCS#12 证书中提取的私钥。
背景
我更喜欢先对 iTextSharp 文档进行电子签名,然后再根据要求进行任何更改/修改。
使用代码
string signerName =
PdfPKCS7.GetSubjectFields(this.myCert.Chain[0]).GetField("CN");
PdfTemplate template = st.SignatureAppearance.GetLayer(2);
template.MoveTo(0, 200);
template.LineTo(500, 0);
template.Stroke();
template.BeginText();
BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,
BaseFont.NOT_EMBEDDED);
template.SetFontAndSize(bf1, 10);
template.SetTextMatrix(1, 1);
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "" +
signerName + "", 0, 40, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
template.SetFontAndSize(bf, 7);
template.SetTextMatrix(1, 1);
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "" +
System.DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss zzz") + "",
50, 30, 0);
template.SetFontAndSize(bf, 7);
template.SetTextMatrix(1, 1);
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Signer:", 0, 25, 0);
template.SetFontAndSize(bf, 7);
template.SetTextMatrix(1, 1);
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "" + "CN=" +
PdfPKCS7.GetSubjectFields(myCert.Chain[0]).GetField("CN") + "",
10, 17, 0);
template.SetFontAndSize(bf, 7);
template.SetTextMatrix(1, 1);
template.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "" + "C=" +
PdfPKCS7.GetSubjectFields(myCert.Chain[0]).GetField("C") + "",
10, 10, 0);
template.EndText();