【问题标题】:"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server“根据验证程序,远程证书无效。”使用 Gmail SMTP 服务器
【发布时间】:2010-10-21 03:03:24
【问题描述】:

我收到此错误:

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

每当我尝试在我的 C# 代码中使用 Gmail 的 SMTP 服务器发送电子邮件时。 有人可以为我指出解决此问题的正确方向吗?

以下是堆栈跟踪...

at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Mail.SmtpConnection.Flush()
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at BulkEmail.frmemail.mailsending(String toaddress, String fromaddress, String fromname, String subject, String pwd, String attachements, String mailmessage, String htmlmessage, Int32 i, Int32 j, String replytoaddress)

【问题讨论】:

  • 您能告诉我们更多关于您使用 Gmail SMTP 服务器的配置吗?我的幸运猜测:您能告诉我们更多关于您的 SSL 安全策略(例如使用有效/无效的 SSL 证书吗?)。
  • 您能给我们一个代码示例,您可以在其中重现错误吗?

标签: c# email smtp


【解决方案1】:

警告:不要在生产代码中使用它!

作为一种解决方法,您可以关闭证书验证。这样做只是为了确认由于证书错误而引发了错误。

在调用smtpclient.Send()之前调用这个方法:

[Obsolete("Do not use this in Production code!!!",true)]
static void NEVER_EAT_POISON_Disable_CertificateValidation()
{
    // Disabling certificate validation can expose you to a man-in-the-middle attack
    // which may allow your encrypted message to be read by an attacker
    // https://stackoverflow.com/a/14907718/740639
    ServicePointManager.ServerCertificateValidationCallback =
        delegate (
            object s,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
        ) {
            return true;
        };
}

【讨论】:

  • 这是一个 hack,而不是修复?
  • 希望看到修复,而不是完全关闭所有安全性。
  • 作为安全问题的解决方法,您可以关闭安全功能吗?什么鬼?
  • 不得不对此投反对票,因为人们似乎仍然认为这是一个解决方案。 只是关闭安全功能。请勿在生产中使用,人们。他甚至这么说。嘘。
  • 赞成。我完全同意这不应该在生产中使用但是..我正在制作一些东西的原型。他们碰巧为我提供的测试服务器迫使我使用 SSL。使用证书对我来说很新鲜,所以我只想要一个QUICK WAY OUT,恕我直言,因为我不会在生产中使用它
【解决方案2】:

这里的链接解决了我的问题。

http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html

我转到 Web 服务的 url(在有问题的服务器上),单击 IE 中的小安全图标,这会显示证书。然后我单击详细信息选项卡,单击复制到文件按钮,这允许我将证书导出为 .cer 文件。在本地获得证书后,我可以使用以下说明将其导入服务器上的证书存储区。

启动一个新的 MMC。 文件 --> 添加/删除管理单元... 单击添加... 选择证书并单击添加。 检查“计算机帐户”单选按钮。点击下一步。

在下一个屏幕中选择客户端计算机。单击完成。 单击关闭。 单击确定。 现在将证书安装到受信任的根证书颁发机构证书存储中。这将允许所有用户信任证书。

【讨论】:

  • +1 通过证书上的导入工具而不是通过管理单元导入证书时,它仅适用于您的用户帐户。使用管理单元允许您选择导入对象、用户帐户、服务帐户或每个人。谢谢你的指点。我在那里挠了一两分钟!
  • 如果您想使用命令行在所有开发/测试工作站上实现自动化 - certutil -f -p test -importPFX Root devcert.pfxcertutil -f -p test -importPFX MY devcert.pfx。需要在管理员命令提示符下运行(假设 PFX 密码为test
  • 如果您使用自签名证书进行测试,这是修复它的最佳方法,感谢 T-Rex!
【解决方案3】:

聚会有点晚了,但如果您正在寻找像 Yury 的解决方案,以下代码将帮助您确定问题是否与自签名证书有关,如果是,则忽略自签名错误。如果您愿意,您显然可以检查其他 SSL 错误。

我们使用的代码(由微软提供 - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx)如下:

  private static bool CertificateValidationCallBack(
         object sender,
         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
         System.Security.Cryptography.X509Certificates.X509Chain chain,
         System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
  // If the certificate is a valid, signed certificate, return true.
  if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
  {
    return true;
  }

  // If there are errors in the certificate chain, look at each error to determine the cause.
  if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
  {
    if (chain != null && chain.ChainStatus != null)
    {
      foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
      {
        if ((certificate.Subject == certificate.Issuer) &&
           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
        {
          // Self-signed certificates with an untrusted root are valid. 
          continue;
        }
        else
        {
          if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
          {
            // If there are any other errors in the certificate chain, the certificate is invalid,
         // so the method returns false.
            return false;
          }
        }
      }
    }

    // When processing reaches this line, the only errors in the certificate chain are 
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
    return true;
  }
  else
  {
 // In all other cases, return false.
    return false;
  }
}

【讨论】:

  • 对于我的情况,sslPolicyErrors 是 RemoteCertificateNameMismatch,我修改了证书检查,因为我们没有相同的 Subject 和 Issuer 值。
  • Exchange 服务器使用的 X509Certificate 不断在自签名证书和受信任证书之间切换。使用此代码帮助我的网络管理员和我不仅发现了这种情况,而且还通过绕过自签名证书完全解决了问题。这是完美的!
【解决方案4】:

您可以通过在证书无效时询问用户是否要继续来改进代码。 要继续吗?如下:

ServicePointManager.ServerCertificateValidationCallback = 
    new RemoteCertificateValidationCallback(ValidateServerCertificate);

并添加这样的方法:

public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;
    else
    {
        if (System.Windows.Forms.MessageBox.Show("The server certificate is not valid.\nAccept?", "Certificate Validation", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            return true;
        else
            return false;
    }
}

【讨论】:

  • 如果这是一个云应用程序,谁会点击“继续”按钮?
【解决方案5】:

我遇到了完全相同的问题,并发现 Avast 防病毒软件的 Mail Shield 默认激活了“扫描 SSL 连接”。请务必将其关闭

据我所知,Avast 会“打开”邮件,扫描邮件中是否存在病毒,然后使用自己的证书对其进行签名,这样邮件就不会被签名通过 gmail 的证书不再产生该错误。

解决方案 1:

  • 从您的防病毒软件(或整个邮件防护罩)中关闭 SSL 扫描。

解决方案 2(应该是最好的安全方案):

  • 以某种方式获取防病毒软件使用的证书(Avast 可以选择导出它)
  • 在连接到 gmail 服务器之前将其导入 imap/pop/smtp 客户端。

【讨论】:

  • 你为我节省了很多时间。会花很长时间才能弄清楚应该归咎于我的防病毒软件而不是我的代码。
  • 感谢您的回复。你为我节省了很多时间。
【解决方案6】:

我知道我在这个游戏中已经很晚了,但我在这里没有看到指向 TLS 流的 system.diagnostics 日志的答案。

在对代码进行任何更改之前,请确保您了解问题所在。 AuthenticationException 是非常通用的异常之一,它并不能说明太多。要了解幕后情况,请编辑应用程序的 app.config 文件(或创建一个新文件)并确保在 system.diagnostics 部分中启用了 System.Net 跟踪源,例如:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" />
    <sharedListeners>
      <add name="file" initializeData="c:\network.log" type="System.Diagnostics.TextWriterTraceListener" />
    </sharedListeners>
    <sources>
      <source name="System.Net" switchValue="Verbose">
        <listeners>
          <add name="file" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
</configuration>

重新运行您的应用程序并检查 c:\network.log 文件。您应该会在此处看到有关您的 TLS (SSL) 连接的详细信息,例如:

System.Net Information: 0 : [12764] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = f44368:535f958, targetName = localhost, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [12764] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=OK).
System.Net Information: 0 : [12764] Remote certificate: [Version]
  V3

[Subject]
  CN=test
  Simple Name: test
  DNS Name: example.com

[Issuer]
  CN=Root CA
  Simple Name: Root CA
  DNS Name: Root CA

...

[Signature Algorithm]
  sha256RSA(1.2.840.113549.1.1.11)

[Public Key]
  Algorithm: RSA
  Length: 2048
  Key Blob: ....
System.Net Information: 0 : [12764] SecureChannel#38496415 - Remote certificate has errors:
System.Net Information: 0 : [12764] SecureChannel#38496415 -    Certificate name mismatch.
System.Net Information: 0 : [12764] SecureChannel#38496415 - Remote certificate was verified as invalid by the user.
System.Net Error: 0 : [12764] Exception in AppDomain#10923418::UnhandledExceptionHandler - The remote certificate is invalid according to the validation procedure..

了解导致问题的原因,您应该能够解决它或至少缩小您的 Google 搜索范围。

【讨论】:

    【解决方案7】:

    由于 ssl 从 Outlook 发送时出现相同的错误。尝试设置 EnableSSL = false 解决了这个问题。

    示例:

    var smtp = new SmtpClient
                    {
                        Host = "smtp.gmail.com",                   
                        Port = 587,
                        EnableSsl = false,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,                   
                        Credentials = new NetworkCredential("xxx@gmail.com", "xxxxx")
                    };
    

    【讨论】:

    • 当您将 SSL 设置为 false 时,gmail 不允许您连接,我尝试了您的解决方案,但它对我不起作用。
    • 是的,这就是我所说的“基本”(相对于“无”或“ssl”)......这些电子邮件设置有时很棘手。
    【解决方案8】:

    您确定您使用的是正确的 SMTP 服务器地址吗?

    smtp.google.com 和 smtp.gmail.com 都可以,但是 SSL 证书是发给第二个的。

    【讨论】:

      【解决方案9】:

      当我尝试通过代理服务器 (Usergate) 使用 SmtpClient 发送电子邮件时,我遇到了同样的错误。

      验证证书包含服务器地址,该地址不等于代理服务器地址,因此出现错误。 我的解决方案:当检查证书出错时,接收证书,导出并检查。

      public static bool RemoteServerCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
          {
              if (sslPolicyErrors == SslPolicyErrors.None)
                  return true;
      
              // if got an cert auth error
              if (sslPolicyErrors != SslPolicyErrors.RemoteCertificateNameMismatch) return false;
              const string sertFileName = "smpthost.cer";
      
              // check if cert file exists
              if (File.Exists(sertFileName))
              {
                  var actualCertificate = X509Certificate.CreateFromCertFile(sertFileName);
                  return certificate.Equals(actualCertificate);
              }
      
              // export and check if cert not exists
              using (var file = File.Create(sertFileName))
              {
                  var cert = certificate.Export(X509ContentType.Cert);
                  file.Write(cert, 0, cert.Length);
              }
              var createdCertificate = X509Certificate.CreateFromCertFile(sertFileName);
              return certificate.Equals(createdCertificate);
          }
      

      我的电子邮件发件人类的完整代码:

      public class EmailSender
      {
          private readonly SmtpClient _smtpServer;
          private readonly MailAddress _fromAddress;
      
          public EmailSender()
          {
              ServicePointManager.ServerCertificateValidationCallback = RemoteServerCertificateValidationCallback;
              _smtpServer = new SmtpClient();
          }
      
          public EmailSender(string smtpHost, int smtpPort, bool enableSsl, string userName, string password, string fromEmail, string fromName) : this()
          {
              _smtpServer.Host = smtpHost;
              _smtpServer.Port = smtpPort;
              _smtpServer.UseDefaultCredentials = false;
              _smtpServer.EnableSsl = enableSsl;
              _smtpServer.Credentials = new NetworkCredential(userName, password);
      
              _fromAddress = new MailAddress(fromEmail, fromName);
          }
      
          public bool Send(string address, string mailSubject, string htmlMessageBody,
              string fileName = null)
          {
              return Send(new List<MailAddress> { new MailAddress(address) }, mailSubject, htmlMessageBody, fileName);
          }
      
          public bool Send(List<MailAddress> addressList, string mailSubject, string htmlMessageBody,
              string fileName = null)
          {
              var mailMessage = new MailMessage();
              try
              {
                  if (_fromAddress != null)
                      mailMessage.From = _fromAddress;
      
                  foreach (var addr in addressList)
                      mailMessage.To.Add(addr);
      
                  mailMessage.SubjectEncoding = Encoding.UTF8;
                  mailMessage.Subject = mailSubject;
      
                  mailMessage.Body = htmlMessageBody;
                  mailMessage.BodyEncoding = Encoding.UTF8;
                  mailMessage.IsBodyHtml = true;
      
                  if ((fileName != null) && (System.IO.File.Exists(fileName)))
                  {
                      var attach = new Attachment(fileName, MediaTypeNames.Application.Octet);
                      attach.ContentDisposition.CreationDate = System.IO.File.GetCreationTime(fileName);
                      attach.ContentDisposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName);
                      attach.ContentDisposition.ReadDate = System.IO.File.GetLastAccessTime(fileName);
                      mailMessage.Attachments.Add(attach);
                  }
                  _smtpServer.Send(mailMessage);
              }
              catch (Exception e)
              {
                  // TODO lor error
                  return false;
              }
              return true;
          }
      
          public static bool RemoteServerCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
      {
          if (sslPolicyErrors == SslPolicyErrors.None)
              return true;
      
          // if got an cert auth error
          if (sslPolicyErrors != SslPolicyErrors.RemoteCertificateNameMismatch) return false;
          const string sertFileName = "smpthost.cer";
      
          // check if cert file exists
          if (File.Exists(sertFileName))
          {
              var actualCertificate = X509Certificate.CreateFromCertFile(sertFileName);
              return certificate.Equals(actualCertificate);
          }
      
          // export and check if cert not exists
          using (var file = File.Create(sertFileName))
          {
              var cert = certificate.Export(X509ContentType.Cert);
              file.Write(cert, 0, cert.Length);
          }
          var createdCertificate = X509Certificate.CreateFromCertFile(sertFileName);
          return certificate.Equals(createdCertificate);
      }
      

      }

      【讨论】:

        【解决方案10】:

        在调用 AuthenticateAsClient 时,我的问题出现在 Windows 2003 Server 上。上述解决方案(例如绕过ServicePointManager.ServerCertificateValidationCallback)不起作用。

        原来这是 Windows 2003 中的一个错误,并且有一个修补程序:

        “使用 Cryptography API 的应用程序无法在 Windows Server 2003 中验证 X.509 证书”

        https://support.microsoft.com/en-us/kb/938397

        安装此修补程序解决了我的问题。

        【讨论】:

          【解决方案11】:

          我的问题不是我通过 IP 地址而不是 URL 来引用服务器。我从 CA 购买了一个签名证书,用于在专用网络中使用。在引用服务器时,证书上指定的 URL 确实很重要。一旦我通过证书中的 URL 引用服务器,一切就开始工作了。

          【讨论】:

          • 这个答案值得上,因为它指出了一个常见的错误;人们(包括我自己)认为Host的目的只是为了找到服务器。
          【解决方案12】:

          您的网站文件夹需要网络服务安全。特别是 web.config。它使用此帐户访问您的证书注册表。这将不再需要向您的代码添加 hack。

          【讨论】:

            【解决方案13】:

            在我们的案例中,问题是由 IIS 服务器证书引起的。证书的主题设置为 DNS 名称,用户试图通过 IP 地址访问网站,因此 .NET 认证验证失败。 当用户开始使用 DNS 名称时,问题就消失了。

            所以您必须将您的 Provider URL 更改为 https://CertificateSubject/xxx/xxx.application

            【讨论】:

            • 你能详细说明一下吗?在我的情况下,应用程序可以在一台服务器上运行,而不能在另一台服务器上运行。我一无所知...我不是专家,但域仍然连接到工作域,并且两台机器上都已经安装了服务器证书。仍然不明白为什么这会是相关的,因为它说的是“远程证书”。
            【解决方案14】:

            检查您计算机的日期和时间。如果有误,更新为当前时间或自动设置为从网上获取时间。

            由于证书绑定到一个固定的时间段,如果你的时钟是错误的,你很可能会得到这样的错误。在这种情况下,通过固定时间,问题将得到解决。

            【讨论】:

            • 如果您的系统日期与当前时间“太远”,则从 google 收到的证书的有效性会导致问题。它看到在当前时间不多的信息上发布并有效。这不是唯一不会导致此问题的事情。但它肯定可以。
            • 一个非常有用的提醒,在我的情况下仔细检查这个!奥卡姆剃刀之类的...... :) 现在关于那个 CMOS 电池......
            【解决方案15】:

            添加这条线对我有用。这实际上信任所有提到的证书here。但是,这主要用于故障排除。如果这对您有用,则意味着远程服务器的证书未作为受信任的证书添加到您的计算机中。

            System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
            

            完整代码是

            private void sendAMail(String toAddress, String messageBody)
                    {
                        String msg = "Sending mail to : " + toAddress;
            
                        MailMessage mail = new MailMessage();
                        mail.To.Add(toAddress);
                        mail.From = new MailAddress("from@mydomain.com");
                        mail.Subject = "Subject: Test Mail";
                        mail.Body = messageBody;
                        mail.IsBodyHtml = true;            
            
                        //Added this line here
                        System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
                        SmtpClient smtp = new SmtpClient();
            
                        smtp.Host = "myhostname.com";            
                        smtp.Credentials = new System.Net.NetworkCredential("sender@sample.com", "");
                        smtp.EnableSsl = true;
                        smtp.Port = 587;            
                        smtp.Send(mail);            
                    }
            
            
            private bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                //Console.WriteLine(certificate);
                return true;
            }
            

            【讨论】:

              【解决方案16】:

              对于那些在使用自签名证书连接到本地站点时遇到同样错误的人,以下博客文章帮助了我。

              http://brainof-dave.blogspot.com.au/2008/08/remote-certificate-is-invalid-according.html

              【讨论】:

                【解决方案17】:

                有一篇关于调查此类问题的 MSDN 博客文章:

                疑难解答 ASP.NET – 根据验证程序,远程证书无效:
                http://blogs.msdn.com/b/jpsanders/archive/2009/09/16/troubleshooting-asp-net-the-remote-certificate-is-invalid-according-to-the-validation-procedure.aspx

                【讨论】:

                • 链接已失效。
                【解决方案18】:

                如果您在使用 AWS 开发工具包将文件上传到 S3 时遇到此错误。确保您为 S3 选择了正确的区域。

                如果您使用了不正确的区域。这将返回这样一个错误,顺便说一句,这并不意味着这个错误。

                【讨论】:

                  【解决方案19】:

                  解决了我的问题

                  smtpClient.Credentials = new NetworkCredential(sendMail.UserName, sendMail.Password);
                  smtpClient.EnableSsl = false;//sendMail.EnableSSL;
                  

                  // 参考 // 问题仅出现 使用上面的行设置 false SSl 以解决在 SMTP 设置中输入用户名和密码时的错误。

                  【讨论】:

                  • 这也关闭了安全性。
                  【解决方案20】:

                  这是我决定使用的解决方案。

                          ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                          {
                              string name = certificate.Subject;
                  
                              DateTime expirationDate = DateTime.Parse(certificate.GetExpirationDateString());
                  
                              if (sslPolicyErrors == SslPolicyErrors.None || (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch && name.EndsWith(".acceptabledomain.com") && expirationDate > DateTime.Now))
                              {
                                  return true;
                              }
                              return false;
                          };
                  

                  【讨论】:

                    【解决方案21】:

                    已接受答案中的代码帮助我调试了问题。然后我意识到certificate 参数的SN 字段与我认为的SMTP 服务器不同。通过将 SmtpClient 实例的 Host 属性设置为证书的 SN 值,我能够解决此问题。

                    【讨论】:

                    • 您能详细说明一下吗?我看到证书的 SN 字段了吗?
                    【解决方案22】:

                    将我的功能用作诊断证书问题 - 见屏幕

                                System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(s As Object,
                                                                                                              cert As System.Security.Cryptography.X509Certificates.X509Certificate,
                                                                                                              chain As System.Security.Cryptography.X509Certificates.X509Chain,
                                                                                                              err As System.Net.Security.SslPolicyErrors)
                                                                                                         Return True
                                                                                                     End Function
                    

                    【讨论】:

                      【解决方案23】:

                      还没有看到有人指出明显的,如果你想安全地调试 SSL 问题,那么总是使用这种方法:

                      #if DEBUG
                          ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                      #endif
                      

                      即使您不小心提交了代码,您仍然可以放心,它不会在发布模式下编译。

                      【讨论】:

                      • 有时在部署调试版本时(对于我来说,在 AWS 开发专用环境中)会设置 DEBUG 符号。所以最好检查调试器是否附加了 if (Debugger.IsAttached) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; }
                      • 我认为这是一个稍微不同的用例,但还是有好处的。
                      【解决方案24】:

                      在 Amazon Linux EC2 虚拟机上运行 dotnet core Web 应用程序时遇到此错误。原来我们有一段时间没有运行sudo yum update 来修补这个服务器,并且安装在机器上的根/中间证书已经过时了。 (具体来说,我们的问题是在 2021-09-30 开始的。)

                      我们运行此命令来更新证书,然后重新启动我们的 dotnet 进程:

                      sudo yum update ca-certificates

                      AWS 支持进一步指出我们针对类似问题的这篇支持文章:Why am I receiving a certificate expiration error for the Let's Encrypt certificate on my EC2 instance?

                      【讨论】:

                        【解决方案25】:

                        以下代码在 dotnetcore 中为我工作以绕过 ssl 证书

                        using (var httpClientHandler = new HttpClientHandler())
                        {                  
                         httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
                          using (var client = new HttpClient(httpClientHandler))
                          {
                          }
                        }
                        

                        【讨论】:

                          猜你喜欢
                          • 2014-11-24
                          • 2016-12-20
                          • 2011-03-28
                          • 2016-11-28
                          • 2013-08-08
                          • 2012-07-20
                          • 2015-03-17
                          相关资源
                          最近更新 更多