Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ssl

sha

My program uses SHA-1 certificate for SSL connection. The SHA-2 certificate has been widely used now by some web services (Gmail) instead. This causes blocking incoming connection to SMTP servers during email notification setup.

To send email I use SmtpClient like this

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);
}

I can't send an email by using this code and I don't want to allow "less secure apps" in my gmail account.

How to implement or switch to SHA-2 certificate for email notifications?

like image 721
Anatoly Avatar asked Sep 04 '15 12:09

Anatoly


2 Answers

SHA-1 vs. SHA-2 is completely unrelated to the problem you have. "Less secure apps" are considered for google the application which don't use OAuth 2.0 for authentication (which would allow for 2-factor authentication) but instead only a simple password. See New Security Measures Will Affect Older (non-OAuth 2.0) Applications for more information.

For using OAuth 2.0 with C# see SMTP and OAuth 2

like image 177
Steffen Ullrich Avatar answered Sep 22 '22 12:09

Steffen Ullrich


Although, SHA1 is more resistant than MD5 to collision attacks, but it is getting weaker each year. Therefore, google encourages to migrate away from SHA-1 to SHA-2/SHA-3.

I think you should first acquire a SHA-2 certificate, and then use the following sample code to set it for 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);

And also notice 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.

like image 22
Hamed Avatar answered Sep 22 '22 12:09

Hamed