如何检查签名文件的数字签名是否由可信证书签名?

时间:2016-07-06 13:50:04

标签: c# pdf itext digital-signature

我开发了适用于pdf文档的应用程序,我要了解我的文档是由可信签名签名的。 我使用itextsharp来获取信息,但我不知道如何检查签名的有效性。

var pdfReader = new PdfReader(document.FilePath);
var acroFields = pdfReader.AcroFields;
var names = acroFields.GetSignatureNames();

    foreach (var name in names)
    {
         var signatureName = name as string;
         var pk = acroFields.VerifySignature(signatureName);
         var signatureIsValid = false;
         foreach (var certificate in pk.Certificates)
         {
             signatureIsValid = certificate.IsValidNow; // It just check date
         }
    }

屏幕下方的文档有两个数字签名,但签名时没有可信任的证书。我必须为用户显示一些类似的消息。

enter image description here

1 个答案:

答案 0 :(得分:4)

要检查受信任的权限,您需要拥有可信的CA证书以进行检查。如果您有一个,您可以使用这样的代码来检查证书是否来自您期望它的受信任的权威机构:

    X509Certificate2 authorityCert = GetAuthorityCertificate();
    X509Certificate2 certificateToCheck = GetYourCertificate();

    X509Chain chain = new X509Chain();
    chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
    chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
    chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
    chain.ChainPolicy.VerificationTime = DateTime.Now;
    chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);

    //Adding your CA root to the chain
    chain.ChainPolicy.ExtraStore.Add(authorityCert);

    bool isChainValid = chain.Build(certificateToCheck);
    if (!isChainValid)
    {
        //Ok, let c what is wrong...
        string[] errors = chain.ChainStatus
            .Select(m => $"{m.StatusInformation.Trim()}, status: {m.Status}")
            .ToArray();

        string certificateErrors = "Error occured during checking certificate.";
        if (errors != null && errors.Length > 0)
            certificateErrors = string.Join(" \n", errors);

        throw new ApplicationException("Trust chain is not from known authority. Errors: " + certificateErrors);
    }

    //Let see if our chain actually contains known root, for which you are cheking
    if (!chain.ChainElements
        .Cast<X509ChainElement>()
        .Any(m => m.Certificate.Thumbprint == authorityCert.Thumbprint))
        throw new ApplicationException("Could not locate CA root!Thumbprints did not match.");