SslStream身份验证失败

时间:2013-10-06 07:37:27

标签: c# ssl

大家,我正在尝试写一些关于SSL的内容,这就是问题所在:

我在下面构建了一些东西:

  • CA证书(自制CA)
  • Server pfx,Server cert,Server key(由自制CA签名为“localhost”)

现在我正在使用.Net SslStream来测试连接:(客户端和服务器位于不同的线程中,并且TCP连接已经构建)

客户端:

sslStream.AuthenticateAsClient("localhost");

服务器:

sslStream.AuthenticateAsServer(serverCert); 
//serverCert is X509Certificate2 built from "server.pfx"

客户端的AuthenticateAsClient方法将抛出异常

“根据验证程序,远程证书无效。”

我想原因是服务器的证书是由不受信任的CA签名的,因此身份验证失败了,那么我怎样才能将CA证书添加到我的信任列表中呢?

我尝试在客户端代码中添加以下代码,但它不起作用

        X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadWrite);
        store.Add(new X509Certificate2(Resources.CACertPath));
        store.Close();
        sslStream.AuthenticateAsClient("localhost");

1 个答案:

答案 0 :(得分:0)

以下代码将避免Windows证书存储并验证链。

我认为没有理由将证书链所需的CA证书添加到证书存储区中的数百个证书库中。这意味着Windows将尝试使用“数百+ 1”证书验证链,而不是真正需要的证书。

默认情况下我想出如何使用此链(chain2),这样就不需要回调了。也就是说,将它安装在ssl套接字上,连接将“正常工作”。而且我想出如何安装它以便传递给回调。也就是说,我必须为每次调用回调构建链。我认为这些是.Net中的架构缺陷,但我可能会遗漏一些明显的东西。

该功能的名称无关紧要。下面,VerifyServerCertificateRemoteCertificateValidationCallback类中的SslStream回调相同。您也可以将其用于ServerCertificateValidationCallback中的ServicePointManager

static bool VerifyServerCertificate(object sender, X509Certificate certificate,
    X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    try
    {
        String CA_FILE = "ca-cert.der";
        X509Certificate2 ca = new X509Certificate2(CA_FILE);

        X509Chain chain2 = new X509Chain();
        chain2.ChainPolicy.ExtraStore.Add(ca);

        // Check all properties
        chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

        // This setup does not have revocation information
        chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

        // Build the chain
        chain2.Build(new X509Certificate2(certificate));

        // Are there any failures from building the chain?
        if (chain2.ChainStatus.Length == 0)
            return true;

        // If there is a status, verify the status is NoError
        bool result = chain2.ChainStatus[0].Status == X509ChainStatusFlags.NoError;
        Debug.Assert(result == true);

        return result;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

    return false;
}