C# Verifying PDF signature

风流意气都作罢 提交于 2020-07-08 03:05:11

问题


Trying to validate PDF signature isn't working. The PDF were signed by Adobe Acrobat and then trying to verify it with the public key of the client certificate.

So I get the public key of the client certificate, hash the PDF and verify if the hash is equal to the pdf signature, but it fails.

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:


First, to verify whether the signature correctly you can simply use the PdfPKCS7 object you already retrieved, more exactly its Verify method:

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

Thus, you can simply call

bool ok = pkcs7.Verify();

and ok is true only if the document hash matches the hash in the signature.


Concerning your attempt to calculate the document hash like this

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

This indeed gives you the hash value of the complete PDF.

For document types with integrated signatures like PDFs, though, this is not the hash of interest because the complete PDF obviously includes the integrated signature!

Thus, you have to find the space reserved for the signature in the PDF and ignore it during hash calculation, cf. this answer on Information Security Stack Exchange, in particular this image:

How integrated PDF signatures are "integrated"

In case of multiple signatures you furthermore have to consider that the earlier signatures only sign a former revision of the PDF, so the hash is to be calculated only for a starting segment of the file, cf. this image from the answer referenced above:

enter link description here

The iText(Sharp) method PdfPKCS7.Verify() takes all this into account.



来源:https://stackoverflow.com/questions/44114464/c-sharp-verifying-pdf-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!