Send encrypted email using certificates in .Net

This is the .net code needed to send encrypted email using secure certificates in .net. Both VB and C# versions are provided below. There is no need to rely on third party components to do this, it is built-in to .net.

The email will then be viewable in any modern email client that supports secure certificates. But it will only be viewable if the email recipient has your certificate installed.

You may create your own private email cetificates using tools like the openssl toolkit. Email certificates are also free at most of the major ssl providers.

Also see the PHP version of encrypted emails on this site that sends encrypted emails.

In VB you must also add a reference to System.Security in your project in Visual Studio Express.

Below are the VB.NET and C# versions of the code for encrypted emails using ssl certificates:

VB code:

    Imports Namespace=System.IO
    Imports System.Net.Mail
    Imports System.Security.Cryptography.X509Certificates
    Imports System.Security.Cryptography.Pkcs

    Class EncryptEmail

    Shared Sub Main(ByVal args() As String)

      SendEncryptedEmail("test.pfx", "test.cer", """Somebody"" ", """Somebody"" ", "Test VB Encrypted HTML EMail", "This email is encrypted and signed.", "localhost", 25, False)

    End Sub

        Shared Sub SendEncryptedEmail(ByVal SigningCertPath As String, ByVal EncryptingCertPath As String, ByVal [To] As String, ByVal From As String, ByVal Subject As String, ByVal Body As String, ByVal SmtpServer As String, ByVal SmtpPort As Integer, ByVal HTML As Boolean)

            Dim SignCert As New X509Certificate2(SigningCertPath, "password")

            Dim EncryptCert As New X509Certificate2(EncryptingCertPath, "")

            Dim Message As New StringBuilder()

            Message.AppendLine("Content-Type: text/" + IIf(HTML, "html", "plain") + "; charset=""iso-8859-1""") 'TODO: For performance reasons this should be changed to nested IF statements

            Message.AppendLine("Content-Transfer-Encoding: 7bit")

            Message.AppendLine()

            Message.AppendLine(Body)

            Dim BodyBytes As Byte() = Encoding.ASCII.GetBytes(Message.ToString())

            Dim ECms As New EnvelopedCms(New ContentInfo(BodyBytes))

            Dim Recipient As New CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, EncryptCert)

            ECms.Encrypt(Recipient)

            Dim EncryptedBytes As Byte() = ECms.Encode()

            Dim Cms As New SignedCms(New ContentInfo(EncryptedBytes))

            Dim Signer As New CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, SignCert)

            Cms.ComputeSignature(Signer)

            Dim SignedBytes As Byte() = Cms.Encode()

            Dim Msg As New MailMessage()

            Msg.To.Add(New MailAddress([To]))

            Msg.From = New MailAddress(From)

            Msg.Subject = Subject

            Dim ms As New MemoryStream(EncryptedBytes)

            Dim av As New AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m")

            Msg.AlternateViews.Add(av)

            Dim smtp As New SmtpClient(SmtpServer, SmtpPort)

            smtp.UseDefaultCredentials = True

            smtp.Send(Msg)

        End Sub

    End Class

C# Code:

    using System;
    using System.IO;
    using System.Text;
    using System.Net.Mail;
    using System.Security.Cryptography.Pkcs;
    using System.Security.Cryptography.X509Certificates;

    namespace EncryptedSMIME

    {

       class Program

       {

           static void Main(string[] args)

           {

               SendEncryptedEmail("Cert.pfx", "thawte.cer",

                   "\"Noah Body\" ",

                   "\"John Doe\" ",

                   "Test C# Encrypted HTML EMail",

                   "This email is encrypted and signed.",

                   "smtp.singingeels.com", 25, false);

           }

    

           static void SendEncryptedEmail(

               string SigningCertPath, string EncryptingCertPath,

               string To, string From, string Subject, string Body,

               string SmtpServer, int SmtpPort, bool HTML)

           {

               X509Certificate2 SignCert = new X509Certificate2(SigningCertPath, "password");

               X509Certificate2 EncryptCert = new X509Certificate2(EncryptingCertPath, "");

    

               StringBuilder Message = new StringBuilder();

               Message.AppendLine("Content-Type: text/" + ((HTML) ? "html" : "plain") +

                   "; charset=\"iso-8859-1\"");

               Message.AppendLine("Content-Transfer-Encoding: 7bit");

               Message.AppendLine();

               Message.AppendLine(Body);

    

               byte[] BodyBytes = Encoding.ASCII.GetBytes(Message.ToString());

    

               EnvelopedCms ECms = new EnvelopedCms(new ContentInfo(BodyBytes));

               CmsRecipient Recipient = new CmsRecipient(

                   SubjectIdentifierType.IssuerAndSerialNumber, EncryptCert);

               ECms.Encrypt(Recipient);

               byte[] EncryptedBytes = ECms.Encode();

    

               SignedCms Cms = new SignedCms(new ContentInfo(EncryptedBytes));

               CmsSigner Signer = new CmsSigner

                   (SubjectIdentifierType.IssuerAndSerialNumber, SignCert);

    

               Cms.ComputeSignature(Signer);

               byte[] SignedBytes = Cms.Encode();

    

               MailMessage Msg = new MailMessage();

               Msg.To.Add(new MailAddress(To));

               Msg.From = new MailAddress(From);

               Msg.Subject = Subject;

    

               MemoryStream ms = new MemoryStream(EncryptedBytes);

               AlternateView av = new AlternateView(ms,

                   "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");

               Msg.AlternateViews.Add(av);

    

               SmtpClient smtp = new SmtpClient(SmtpServer, SmtpPort);

               smtp.UseDefaultCredentials = true;

               smtp.Send(Msg);

           }

       }

    }


Technorati Tags:

4 Responses to Send encrypted email using certificates in .Net

Leave a Reply to Jane Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>