TrustAllCertificatesCallback被忽略

时间:2010-07-22 18:57:03

标签: .net ssl powershell

给定网址或服务器名称,如何使用powershell或.net库下载Web服务器正在使用的(过期)证书,然后将其保存到文件或将其导入我的证书存储区?

谢谢!

我取得了进步,我在这个问题上做得很远:

static class Program
    {
        static void Main()
        {
            ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatesCallback;
            var tcpclient = new TcpClient("remote.example.com", 443);
            var tcpstream = tcpclient.GetStream();
            var sslstream = new SslStream(tcpstream);
            sslstream.AuthenticateAsClient("remote.example.com");
            X509Certificate rc = sslstream.RemoteCertificate;
            Console.WriteLine(rc.ToString());
            Console.ReadLine();
        }

        public static bool TrustAllCertificatesCallback(
            object sender, X509Certificate cert,
            X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true;
        }
    }

现在,当我运行这个程序时,我在AuthenticateAsClient行上得到一个AuthenticationException,它说“远程证书根据验证程序无效”。我在return true;上使用断点运行它,它从未调用TrustAllCertificatesCallback。我认为程序集存在权限或配置问题,是否有人知道如何修复它?

1 个答案:

答案 0 :(得分:9)

我没有做过这样的事情,但看看这些例子我觉得我可以看出出了什么问题。试试这段代码:

static class Program
{
    static void Main()
    {
        var tcpclient = new TcpClient("remote.example.com", 443);
        var tcpstream = tcpclient.GetStream();
        var sslstream = new SslStream(tcpstream, false, new RemoteCertificateValidationCallback (TrustAllCertificatesCallback));
        sslstream.AuthenticateAsClient("remote.example.com");
        X509Certificate rc = sslstream.RemoteCertificate;
        Console.WriteLine(rc.ToString());
        Console.ReadLine();
    }

    public static bool TrustAllCertificatesCallback(
        object sender, X509Certificate cert,
        X509Chain chain, System.Net.Security.SslPolicyErrors errors)
    {
        return true;
    }
}