C# 验证 PDF 签名

A77*_*7ak 2 c# pdf rsa itext digital-signature

尝试验证 PDF 签名不起作用。PDF 由 Adob​​e Acrobat 签名,然后尝试使用客户端证书的公钥对其进行验证。

所以我得到了客户端证书的公钥,对 PDF 进行散列并验证散列是否等于 pdf 签名,但它失败了。

HttpClientCertificate cert = request.ClientCertificate;
X509Certificate2 cert2 = new X509Certificate2(cert.Certificate);

PdfReader pdfreader = new PdfReader("path_to_file");

AcroFields fields = pdfreader.AcroFields;
AcroFields.Item item = fields.GetFieldItem("Signature1");
List<string> names = fields.GetSignatureNames();

foreach (string name in names){
     PdfDictionary dict = fields.GetSignatureDictionary(name);
     PdfPKCS7 pkcs7 = fields.VerifySignature(name);
     Org.BouncyCastle.X509.X509Certificate pdfSign = pkcs7.SigningCertificate;

     // Get its associated CSP and public key
     RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert2.PublicKey.Key;

     // Hash the data
     SHA256 sha256 = new SHA256Managed();

     byte[] pdfBytes = System.IO.File.ReadAllBytes("path_to_pdf");
     byte[] hash = sha256.ComputeHash(pdfBytes);

     // Verify the signature with the hash
     bool ok = csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), pdfSing.GetSignature());
 }
Run Code Online (Sandbox Code Playgroud)

mkl*_*mkl 7

首先,要验证签名是否正确,您可以简单地使用PdfPKCS7您已经检索到的对象,更准确地说是它的Verify方法:

/**
 * Verify the digest.
 * @throws SignatureException on error
 * @return <CODE>true</CODE> if the signature checks out, <CODE>false</CODE> otherwise
 */
virtual public bool Verify()
Run Code Online (Sandbox Code Playgroud)

因此,您可以简单地调用

bool ok = pkcs7.Verify();
Run Code Online (Sandbox Code Playgroud)

而且oktrue只有当文件哈希签名中的散列相匹配。


关于您尝试像这样计算文档哈希

byte[] pdfBytes = System.IO.File.ReadAllBytes("path_to_pdf");
byte[] hash = sha256.ComputeHash(pdfBytes);
Run Code Online (Sandbox Code Playgroud)

这确实为您提供了完整 PDF的哈希值。

但是,对于具有集成签名的文档类型(如 PDF),这不是感兴趣的散列,因为完整的 PDF 显然包含集成签名!

因此,您必须在 PDF 中找到为签名保留的空间,并在哈希计算过程中忽略它,参见。这个关于信息安全堆栈交换的答案,特别是这张图片:

集成的 PDF 签名是如何“集成”的

在多重签名的情况下,您还必须考虑到较早的签名仅对 PDF 的先前修订版签名,因此仅针对文件的起始段计算散列,参见。上面引用答案中的这张图片:

在此处输入链接描述

iText(Sharp) 方法PdfPKCS7.Verify()将所有这些都考虑在内。