2

我正在开发 WCF Web 服务来检查 XML 签名中的证书是否有效。XML 使用合格且有效的 X509 证书进行签名。当我在 Visual Studio 开发环境中运行服务时,X509Certificate2.Verify() 和 X509Chain.Build() 方法返回 TRUE。但是当我在 IIS 下发布我的服务时,这些方法返回 FALSE。我做错了什么或缺少什么?这是我的验证码:

    public static void VerifyXml(XmlDocument xDoc)
    {
        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xDoc);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xDoc.GetElementsByTagName("Signature");

        // Load the first <signature> node.  
        signedXml.LoadXml((XmlElement)nodeList[0]);

        IEnumerable<KeyInfoX509Data> x509Data = signedXml.KeyInfo.Cast<KeyInfoX509Data>();
        KeyInfoX509Data info = x509Data.First<KeyInfoX509Data>();
        X509Certificate2 cert = info.Certificates[0] as X509Certificate2;

        bool certIsValid = cert.Verify();
        // Here I receive TRUE in development environment and FALSE under IIS
        if (!certIsValid)
            throw new X509Exception("Invalid certificate");

        bool chainIsValid = false;
        X509Chain chain = new X509Chain();
        chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
        chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
        chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
        chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
        chainIsValid = chain.Build(cert);
        // Here I also receive TRUE in development environment and FALSE under IIS
        if (!chainIsValid)
            throw new X509Exception("Chain is invalid");

        // Check the signature
        bool signatureOK = signedXml.CheckSignature(cert, false);
        if (!signatureOK)
            throw new X509Exception("Signature is invalid");
     }

有任何想法吗?谢谢

4

1 回答 1

4

根证书在哪里?我认为 ASP.NET 将使用本地机器存储——也许 VS 开发服务器使用用户存储并在那里找到根证书但 ASP.NET 没有找到它?尝试将根证书添加到本地机器存储。

您可以查看 X509Chain 中的状态以获取更多详细信息:

foreach (X509ChainElement element in chain.ChainElements)
{
    Console.WriteLine ("Element issuer name: {0}", element.Certificate.Issuer);
    Console.WriteLine ("Element certificate valid until: {0}", element.Certificate.NotAfter);
    Console.WriteLine ("Element certificate is valid: {0}", element.Certificate.Verify ());
    Console.WriteLine ("Element error status length: {0}", element.ChainElementStatus.Length);
    Console.WriteLine ("Element information: {0}", element.Information);
    Console.WriteLine ("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);

    if (ch.ChainStatus.Length > 1)
    {
        for (int index = 0; index < element.ChainElementStatus.Length; index++)
        {
            Console.WriteLine (element.ChainElementStatus[index].Status);
            Console.WriteLine (element.ChainElementStatus[index].StatusInformation);
        }
    }
}
于 2009-08-14T14:25:57.030 回答