C#不信任安装的证书

问题描述:

我成立了一个FTP服务器IIS与我创造了我自己(使用Makecert.exePvk2Pfx)的SSL证书。我将PFX文件归因于我的FTP服务器。C#不信任安装的证书

我有连接到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时,我看到了我的证书。

+0

没有给出什么理由不相信? – Ben

+0

答案对你有帮助吗?如果是这样,请接受答案,如果没有添加信息澄清。 – Sascha

+0

我很抱歉Sascha,但我无法立即回答您。我忙于另一个重点项目。我会尽快澄清。感谢您的帮助。 – Jeppen

通常,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

作为一个快速的解决方法,你可以接受所有的证书:

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