Encrypt Email in C# - S/MIME with RC2, 3DES and AES (RSAES-OAEP)

In previous section, I introduced how to send email with digital signature. In this section, I will introduce how to encrypt email with digital certificate in C#.

Introduction

After the recipient received your email with digital signature, the recipient can get your digital certificate public key from your digital signature. Then the recipient can encrypt an email with your public key and send it to you. Only you can decrypt this email with your private key. That is how S/MIME can protect your email content. If you don’t expose your digital certificate private key to others, none can read your email which is encrypted by your public key.

If you received an email with digital signature, your email client usually stores the public key of the sender in “Control Panel” -> “Internet Options” -> “Content” -> “Certificates” -> “Other People”.

Then you can use the following code to encrypt email and send it to your recipient.

Note

Remarks: All of samples in this section are based on first section: Send email in a simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[C# - Encrypt Email (S/MIME) - Example]

The following example codes demonstrate how to encrypt email with digital certificate in C#.

Note

To get the full sample projects, please refer to Samples section.

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using EASendMail; //add EASendMail namespace

namespace mysendemail
{
    class Program
    {
        static X509Certificate2 _findCertificate(string storeName, string emailAddress)
        {
            X509Certificate2 cert = null;

            X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection certfiicates = store.Certificates.Find(X509FindType.FindBySubjectName, emailAddress, true);
            if (certfiicates.Count > 0)
            {
                cert = certfiicates[0];
            }

            store.Close();

            return cert;
        }

        static void Main(string[] args)
        {
            try
            {
                SmtpMail oMail = new SmtpMail("TryIt");

                // Set sender email address, please change it to yours
                oMail.From = "test@emailarchitect.net";
                // Set recipient email address, please change it to yours
                oMail.To = "support@emailarchitect.net";

                // Set email subject
                oMail.Subject = "test encrypted email";
                // Set email body
                oMail.TextBody = "this is a test email with email encryption";

                X509Certificate2 signerCertificate = _findCertificate("My", oMail.From.Address);
                if (signerCertificate == null)
                    throw new Exception("No signer certificate found for " + oMail.From.Address + "!");

                oMail.From.Certificate2 = signerCertificate;

                // You can also load the signer certificate from a pfx file.
                /* string pfxPath = "D:\\TestCerts\\signer.pfx";
                X509Certificate2 signerCertFromPfx = new X509Certificate2(pfxPath,
                    "nosecret",
                    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);

                oMail.From.Certificate2 = signerCertFromPfx;
                */
                // If you use it in web application,
                // please use  X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet

                // If you use it in .NET core application
                // please use X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet

                int count = oMail.To.Count;
                for (int i = 0; i < count; i++)
                {
                    MailAddress oAddress = oMail.To[i] as MailAddress;
                    X509Certificate2 encryptCert = _findCertificate("AddressBook", oAddress.Address);
                    if (encryptCert == null)
                        encryptCert = _findCertificate("My", oAddress.Address);

                    if (encryptCert == null)
                        throw new Exception("No encryption certificate found for " + oAddress.Address + "!");

                    oAddress.Certificate2 = encryptCert;

                    // You can also load the encryptor certificate from a cer file like this
                    /*
                    string cerPath = "D:\\TestCerts\\encryptor.cer";
                    X509Certificate2 encryptCertFromFile = new X509Certificate2(cerPath);
                    oAddress.Certificate2 = encryptCertFromFile;
                    */
                }

                // Your SMTP server address
                SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");

                //User and password for ESMTP authentication, if your server doesn't require
                //User authentication, please remove the following codes.
                oServer.User = "test@emailarchitect.net";
                oServer.Password = "testpassword";

                // Most mordern SMTP servers require SSL/TLS connection now.
                // ConnectTryTLS means if server supports SSL/TLS, SSL/TLS will be used automatically.
                oServer.ConnectType = SmtpConnectType.ConnectTryTLS;

                // If your SMTP server uses 587 port
                // oServer.Port = 587;

                // If your SMTP server requires SSL/TLS connection on 25/587/465 port
                // oServer.Port = 25; // 25 or 587 or 465
                // oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                Console.WriteLine("start to send encrypted email ...");

                SmtpClient oSmtp = new SmtpClient();
                oSmtp.SendMail(oServer, oMail);

                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
    }
}

If you received digital signed and encrypted email by Windows Mail(Outlook Express), it looks like this:

c# sign and encrypt email

Encryption Algorithm

You can use SmtpMail.EncryptionAlgorithm property to set RC2, RC4, 3DES, AES128, AES192 or AES256 encryption algorithm. RSAES-OAEP (AES128, AES192 and AES256) is recommended.

RSA-OAEP Encryption with SHA256 HASH

If you need to use RSA-OAEP encryption with sha256 scheme based on EDIFACT rule, please have a look at this topic:

RSASSA-PSS + RSA-OAEP Encryption with SHA256 hash algorithm

Next Section

At next section I will introduce how to send email with event handler.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.