C#不信任已安装的证书

时间:2012-06-26 12:54:14

标签: c# iis ftp x509certificate2

我在FTP中设置了一个IIS服务器,其中包含SSL证书,我创建了自己(使用Makecert.exePvk2Pfx)。我将PFX文件归因于我的FTP服务器。

我有一个连接到FTP服务器的C#脚本,并且始终收到以下错误消息:

  

System.Security.Authentication.AuthenticationException:根据验证程序,远程证书无效。

我在当地计算机和用户的“受信任的根证书颁发机构”中安装了证书。

由于它没有验证,我通过商店的C#看了一眼:

X509Store store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

foreach (X509Certificate2 mCert in store.Certificates)
{
     var friendlyName = mCert.Issuer;
     Console.WriteLine(friendlyName);
}
store.Close();

但我的证书没有列出。当我打开MMC console 时,我会看到我的证书。

2 个答案:

答案 0 :(得分:2)

通常,C#不信任没有受信任的根证书的证书 - 就像自签名证书一样。 ServicePointManager允许添加一个您可以自己处理信任的函数。

// Callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(
    object sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors policyErrors)
{
    if (Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreSslErrors"]))
    {
        // Allow any old dodgy certificate...
        return true;
    }
    else
    {
        return policyErrors == SslPolicyErrors.None;
    }
}

private static string MakeRequest(string uri, string method, WebProxy proxy)
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.AllowAutoRedirect = true;
    webRequest.Method = method;

    // Allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
    ValidateRemoteCertificate);

    if (proxy != null)
    {
        webRequest.Proxy = proxy;
    }

    HttpWebResponse response = null;
    try
    {
        response = (HttpWebResponse)webRequest.GetResponse();
        using (Stream s = response.GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(s))
            {
                return sr.ReadToEnd();
            }
        }
    }
    finally
    {
        if (response != null)
            response.Close();
    }
}

来自博客文章 How to accept an invalid SSL certificate programmatically

答案 1 :(得分:1)

作为一种快速解决方法,您可以接受以下所有证书:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;