如何在使用 SHA-2 而不是 SHA-1 之间切换?

How to switch between using SHA-2 instead of SHA-1?

我的程序使用 SHA-1 证书进行 SSL 连接。 SHA-2 证书现在已被一些网络服务(Gmail)广泛使用。这会导致在电子邮件通知设置期间阻止与 SMTP 服务器的传入连接。

为了发送电子邮件,我像这样使用 SmtpClient

using (var smtpClient = new SmtpClient(serverSettings.SmtpServerName, (int)serverSettings.SmtpPort))
{
     smtpClient.EnableSsl = serverSettings.SmtpUseSsl;
     smtpClient.UseDefaultCredentials = false; 

     if (!string.IsNullOrEmpty(serverSettings.UserName) || !string.IsNullOrEmpty(serverSettings.EncryptedPassword))
     {
          smtpClient.Credentials = new NetworkCredential(serverSettings.UserName, serverSettings.EncryptedPassword);
     }
                ...
      smtpClient.Send(message);
}

我无法使用此代码发送电子邮件,我不想在我的 Gmail 帐户中允许 "less secure apps"。

如何为电子邮件通知实施或切换到 SHA-2 证书?

SHA-1 与 SHA-2 与您遇到的问题完全无关。 "Less secure apps" 被考虑用于 google 不使用 OAuth 2.0 进行身份验证(允许双因素身份验证)但仅使用简单密码的应用程序。有关详细信息,请参阅 New Security Measures Will Affect Older (non-OAuth 2.0) Applications

要将 OAuth 2.0 与 C# 结合使用,请参阅 SMTP and OAuth 2

虽然SHA1比MD5更能抵抗碰撞攻击,但是一年比一年弱。因此,google 鼓励从 SHA-1 迁移到 SHA-2/SHA-3。

我认为您应该先获取一个 SHA-2 证书,然后使用以下示例代码为 SMTPClient 设置它:

string certificate = "Certificate.cer";

X509Certificate cert = new X509Certificate2(certificate);

MailMessage message = new MailMessage(from, to);

SmtpClient client = new SmtpClient(server);

client.ClientCertificates.Add(cert);

client.Send(message);

还要注意 MSDN SmtpClient.ClientCertificates remarks:

The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if possible. When attempting to reuse an SSL session, the Framework uses the first element of ClientCertificates (if there is one), or tries to reuse an anonymous sessions if ClientCertificates is empty.