C#验证PDF签名

时间:2017-05-22 13:41:52

标签: c# pdf itext rsa digital-signature

尝试验证PDF签名无效。 PDF由Adobe 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());
 }

1 个答案:

答案 0 :(得分:3)

首先,要验证签名是否正确,您只需使用已检索的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()

因此,您只需致电

即可
bool ok = pkcs7.Verify();
仅当文档哈希与签名中的哈希匹配时,

ok才为true

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

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

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

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

因此,您必须在PDF中找到为签名保留的空间,并在哈希计算期间忽略它,参见信息安全堆栈交换this answer,特别是此图像:

How integrated PDF signatures are "integrated"

在多个签名的情况下,您还必须考虑早期签名仅签署PDF的以前版本,因此仅针对文件的起始段计算散列,参见这张图片来自answer referenced above

enter link description here

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