【发布时间】:2010-06-09 21:37:58
【问题描述】:
尝试使用 C# 发送安全电子邮件,想知道我是否理解正确。我目前有以下程序:
using System;
using System.Net.Mail;
using System.Net;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Net.Security;
namespace Geekality.SecureEmail
{
class Program
{
static bool OurCertificateValidation(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var actualCertificate = X509Certificate.CreateFromCertFile("example.com.cert");
return certificate.Equals(actualCertificate);
}
static void Main(string[] args)
{
// Register our own certificate validation
ServicePointManager.ServerCertificateValidationCallback = OurCertificateValidation;
// Message
var from = new MailAddress("me@example.com", "Me");
var to = new MailAddress("you@example.com", "Myself");
var message = new MailMessage(from, to)
{
Subject = "Greetings!",
Body = "How are you doing today?",
};
// Create client
var client = new SmtpClient("smtp.example.com")
{
EnableSsl = true,
Credentials = new NetworkCredential
{
UserName = "me@example.com",
Password = "password",
},
};
// Try to send
using (client)
{
try
{
client.Send(message);
Console.WriteLine("Message sent!");
}
catch (AuthenticationException e)
{
Console.WriteLine("Authentication failed:");
Console.WriteLine(e.Message);
}
catch (SmtpException e)
{
Console.WriteLine("SMTP error:");
Console.WriteLine(e.Message);
}
}
Console.ReadKey(true);
}
}
}
当然,数据已更改为示例值。无论如何,从我所见,这似乎工作得很好。关于我所做的任何事情?特别是关于我如何进行证书验证的问题。这是一个好方法吗?还是我在这里错过了一些糟糕的事情,以至于我还不如不使用 SSL 发送电子邮件?
我自己进行验证的原因是默认验证失败,因为它是自颁发的证书,并且我使用的邮件域与使用的证书中的不同。我正在使用 mail.mydomain.com,而证书中的域类似于 mywebhost.com。所以我所做的是使用它的邮件客户端从 Opera 获取证书文件并将其存储,以便我可以将其与尝试发送电子邮件时获得的文件进行比较。这是进行此验证的安全且良好的方法吗?我也知道实际证书的哈希值,并试图用它与我在发送电子邮件时得到的哈希值进行比较。这也有效并且更容易做到,尽管在代码行中它几乎相同。只需与字符串而不是文件进行比较。这些方法中的任何一种都比另一种更好吗?
【问题讨论】:
标签: c# validation email ssl ssl-certificate