C#轻松实现为Word文档添加数字签名
作者:秋天的落叶铺满小路
在折腾电子合同或正式报告时,给 Word 文档加上数字签名几乎是刚需——既能证明文档没被篡改,又能确认是谁签的。今天分享一个用C#快速搞定这件事的小办法,主角是 Free Spire.Doc for .NET 这个免费库,代码量很少,几分钟就能跑起来。
准备工作
安装 Free Spire.Doc
通过 NuGet 包管理器搜索 FreeSpire.Doc 并安装,或直接下载 DLL 引用。
准备数字证书
你需要一个有效的 .pfx 格式数字证书文件及对应的密码。certificate.pfx 是什么东西呢?简单说,它就是你的“数字身份证”。里面包含了你的公钥、私钥以及身份信息。.pfx 格式通常带有密码保护,你用这个文件给 Word 文档盖章,别人打开文档就能看到是谁签的,同时还能检验文档是否被改过。
你可以从 CA 机构(比如沃通、DigiCert 等)申请一个真正的商用证书,也可以本地自己生成一个测试用的——开发阶段用 makecert 或 OpenSSL 随便搞一个就行,只不过正式给别人看的时候 Word 会提示“签名无效”。
代码实现
下面是一个完整的控制台程序示例,演示加载 Word 文档、加载证书并签名保存。
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
// 创建 Document 对象
Document doc = new Document();
// 加载需要签名的 Word 文件
doc.LoadFromFile("Input.docx");
// 指定证书路径和密码
string certificatePath = "certificate.pfx";
string password = "password";
// 数字签名并保存为 Docx2013 格式
doc.SaveToFile("DigitallySigned.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}代码解析
- 加载文档 :通过
Document.LoadFromFile载入待签名的.docx文件。 - 证书配置 :
certificatePath和password分别指向证书文件路径和密码。 - 保存签名 :
SaveToFile方法重载中指定输出格式(如 Docx2013)、证书路径和密码,即可在保存时完成签名。
签名完成后,用 Word 打开 DigitallySigned.docx,文档顶部会显示“签名行”,状态栏提示“已签名的文档”,签名详细信息可查阅“文件”->“信息”->“查看签名”。
重要提示
- 免费版限制 :免费版 Spire.Doc 对文档大小有限制:支持处理的 Word 文档 不超过 500 个段落或 25 个表格 (以先达到者为准)。对于大多数小型办公文档和合同,这一限制已足够使用。
- 证书有效性 :生产环境中请使用由受信任CA颁发的证书,否则Word会提示签名无效。
- 支持格式 :
SaveToFile的FileFormat参数可选Docx2010、Docx2013、Docx2016等,请根据实际需要选择。 - 仅对新文件生效 :数字签名是在保存新文件时附加的,原文件不受影响。
知识扩展
给 Word 文档添加数字签名,在 C# 中有多种实现方式。以下是几种主流方案的完整代码示例和使用说明。
数字签名与数字证书
在开始编码之前,需要理解两个基础概念:
- 数字签名:一种电子形式的签名,用于验证签名者的身份并确保文档未被篡改。
- 数字证书(.pfx 文件):创建数字签名的关键,包含公钥和签名者的身份信息,供他人验证签名真伪。
你需要准备一个有效的 .pfx 证书文件及其密码才能进行数字签名。若无可用证书,可通过 I love PDF 获取权威 CA 签发的证书,或使用 OpenSSL 生成自签名证书用于开发测试。
方案一:Aspose.Words for .NET(推荐)
Aspose.Words 是功能最全面的商业库,支持基础签名、签名行添加、批量签名等多种场景。
步骤 1:安装 NuGet 包
在 Visual Studio 的“程序包管理器控制台”中执行:
Install-Package Aspose.Words
步骤 2:导入必要的命名空间
using Aspose.Words; using Aspose.Words.Saving; using System.Security.Cryptography.X509Certificates;
场景 A:为现有 Word 文档添加数字签名(基础版)
using Aspose.Words;
using Aspose.Words.Saving;
string dataDir = @"C:\YourDocumentDirectory\";
// 加载数字证书
CertificateHolder certHolder = CertificateHolder.Create(dataDir + "morzal.pfx", "aw");
// 加载待签名的 Word 文档
Document doc = new Document(dataDir + "Digitally signed.docx");
// 对文档进行数字签名并保存
DigitalSignatureUtil.Sign(dataDir + "Digitally signed.docx",
dataDir + "Document.Signed.docx",
certHolder);代码说明:DigitalSignatureUtil.Sign 的第一个参数是原始文档路径,第二个是签名后的输出路径,第三个是证书持有者。
场景 B:为文档添加签名行并签名(可视化签名)
如果希望在文档中创建一个可视化的签名行区域,可以使用以下代码:
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Signing;
string dataDir = @"C:\YourDocumentDirectory\";
// 创建新文档
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// 插入签名行
SignatureLine signatureLine = builder.InsertSignatureLine(new SignatureLineOptions()).SignatureLine;
// 保存带有签名行的中间文档
doc.Save(dataDir + "SignDocuments.SignatureLine.docx");
// 配置签名选项
SignOptions signOptions = new SignOptions
{
SignatureLineId = signatureLine.Id,
SignatureLineImage = File.ReadAllBytes(dataDir + "signature_image.png") // 可选签名图像
};
// 加载证书
CertificateHolder certHolder = CertificateHolder.Create(dataDir + "morzal.pfx", "aw");
// 对包含签名行的文档进行数字签名
DigitalSignatureUtil.Sign(dataDir + "SignDocuments.SignatureLine.docx",
dataDir + "SignDocuments.NewSignatureLine.docx",
certHolder, signOptions);场景 C:批量签名多个文档
string[] documents = { "doc1.docx", "doc2.docx", "doc3.docx" };
string certPath = @"C:\Cert\mycert.pfx";
string password = "your_password";
string outputDir = @"C:\SignedOutput\";
CertificateHolder certHolder = CertificateHolder.Create(certPath, password);
foreach (string docName in documents)
{
string inputPath = Path.Combine(dataDir, docName);
string outputPath = Path.Combine(outputDir, "signed_" + docName);
DigitalSignatureUtil.Sign(inputPath, outputPath, certHolder);
Console.WriteLine($"已签名: {docName}");
}方案二:Spire.Doc for .NET
Spire.Doc 是国内团队开发的高性能 Word 文档处理库,无需安装 Microsoft Office,且原生支持 WPS 格式。
步骤 1:安装 NuGet 包
Install-Package Spire.Doc
步骤 2:基础签名代码
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
// 创建 Document 对象
Document doc = new Document();
// 加载 Word 文档
doc.LoadFromFile(@"C:\sample.docx");
// 指定 .pfx 证书路径和密码
string certificatePath = @"C:\cert\gary.pfx";
string password = "your_cert_password";
// 保存文档并添加数字签名
doc.SaveToFile("AddDigitalSignature.docx",
FileFormat.Docx2013,
certificatePath,
password);
}
}
}更多签名方式(SaveToStream / Sign 静态方法)
Spire.Doc 提供多种签名方式:
方式一:保存到流(SaveToStream)
Document doc = new Document("sample.docx");
FileStream fs = new FileStream("output.docx", FileMode.Create);
doc.SaveToStream(fs, FileFormat.Docx2013, "gary.pfx", "e-iceblue");
fs.Flush();方式二:静态 Sign 方法
FileStream fs = File.OpenRead("sample.docx");
byte[] result = Document.Sign(fs, "gary.pfx", "e-iceblue");
File.WriteAllBytes("AddDigitalSignature.docx", result);方案三:GroupDocs.Signature for .NET
GroupDocs.Signature 支持超过 60 种文件格式,提供了更丰富的签名选项(文本、图像、二维码、条形码等)。
步骤 1:安装 NuGet 包
dotnet add package GroupDocs.Signature
步骤 2:基础签名代码
using GroupDocs.Signature;
using GroupDocs.Signature.Options;
using (Signature signature = new Signature("input.docx"))
{
DigitalSignOptions options = new DigitalSignOptions("certificate.pfx")
{
Password = "1234567890", // 证书密码
PageNumber = 1, // 签名所在页码
Left = 50, // 距左侧距离(像素)
Top = 50, // 距顶部距离(像素)
Reason = "Document security check", // 签名原因
Contact = "John Smith", // 联系人信息
Location = "Office D.W." // 签名地点
};
SignResult result = signature.Sign("output.docx", options);
}场景 B:带可视化呈现的签名
DigitalSignOptions options = new DigitalSignOptions("certificate.pfx")
{
Password = "1234567890",
Reason = "Security issue",
Contact = "John Smith",
Location = "Office D.W.",
ImageFilePath = "signature.png", // 指定签名图像
AllPages = true, // 在所有页面上显示
VerticalAlignment = VerticalAlignment.Center, // 垂直对齐方式
HorizontalAlignment = HorizontalAlignment.Left, // 水平对齐方式
Width = 60, // 签名宽度
Height = 80, // 签名高度
Margin = new Padding() { Bottom = 10, Right = 10 }
};方案四:GemBox.Document(轻量级)
GemBox.Document 是一个轻量级的高性能库,API 设计简洁。
步骤 1:安装 NuGet 包
Install-Package GemBox.Document
步骤 2:基础签名代码
using GemBox.Document;
class Program
{
static void Main()
{
ComponentInfo.SetLicense("FREE-LIMITED-KEY"); // 免费版需要 License Key
var document = DocumentModel.Load("input.docx");
var saveOptions = new DocxSaveOptions();
saveOptions.DigitalSignatures.Add(new DocxDigitalSignatureSaveOptions()
{
CertificatePath = "certificate.pfx",
CertificatePassword = "your_password"
});
document.Save("signed_output.docx", saveOptions);
}
}方案五:Wordize(专门签名方案)
Wordize 专注于 Word 文档的数字签名功能。
using Wordize.DigitalSignatures;
CertificateHolder certificateHolder = CertificateHolder.Create("certificate.pfx", "Password");
Signer.Sign("input.docx", "output.docx", certificateHolder);总结
借助 Free Spire.Doc for .NET,只需几行代码即可在 C# 中为 Word 文档添加数字签名,非常适合批量处理合同、报告等文件的自动化场景。但务必关注免费版的段落/表格数量限制,避免运行时异常。如果需求超出限制,可评估商业许可或采用分治法。希望本文能帮助你快速上手文档签名功能!
到此这篇关于C#轻松实现为Word文档添加数字签名的文章就介绍到这了,更多相关C# Word添加数字签名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
