C# PDF添加可信时间戳数字签名

以PDF格式保存的电子交易文件或合同,即使具有数字签名,仍然不能完全保证该文件的法律效力,因为数字证书存在有效期和可随时吊销的问题。为了解决这一问题,出现了一种改进的基于时间戳的数字签名方案,即在数字签名的基础上打上一个可信赖的时间戳。

这篇将介绍如何使用.NET PDF组件Spire.PDF for .NET在C#应用程序中给PDF文档添加数字签名并打上时间戳(注意这里的时间戳必须符合RFC 3161标准)。

引用DLL

在使用以下代码前,需要引用Spire.PDF for .NET组件的DLL文件到工程中。官网可以下载最新版的DLL文件,下载地址。此外,也可以通过NuGet Package Manager搜索Spire.PDF for .NET然后点击安装。

示例代码

在进行签名前,需要准备以下资料:

1)数字证书和密码;

2)时间戳服务器的URL地址(本文使用的地址是http://timestamp.wosign.com/rfc3161);

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Security;

namespace Digitally_Sign_Pdf_with_Timestamp
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Additional.pdf");

            //获取第一页
            PdfPageBase page = pdf.Pages[0];

            //加载数字证书(.pfx文件)
            PdfCertificate cert = new PdfCertificate("test.pfx", "123");

            //加载一张图片
            Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile("Logo.jpg");

            //添加跟图片一样大小的签名到第一页,并设置图片为签名图片
            Spire.Pdf.Security.PdfSignature signature = new Spire.Pdf.Security.PdfSignature(page.Document, page, cert, "sign1");
            signature.Bounds = new RectangleF(new PointF(100, 300), new SizeF(image.Width, image.Height));
            signature.SignImageSource = image;
            signature.GraphicsMode = Spire.Pdf.Security.GraphicMode.SignImageAndSignDetail;
            signature.SignImageLayout = Spire.Pdf.Security.SignImageLayout.Stretch;
            signature.DocumentPermissions = Spire.Pdf.Security.PdfCertificationFlags.AllowFormFill | Spire.Pdf.Security.PdfCertificationFlags.AllowComments;

            //配置时间戳服务器
            string url = "http://timestamp.wosign.com/rfc3161";
            signature.ConfigureTimestamp(url);

            //保存文档
            pdf.SaveToFile("output.pdf");
        }
    }
}

效果:

C# PDF添加可信时间戳数字签名