Home > C# > Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail)

Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail)

Final part in the serie c# encrypting mail.

So now we got the content build and signed. Now what is left to do i encrypting the content.

In this post we have a look at how the structure of the content should just before it is encrypted, and how to encrypt the content.

Link to part 1, part 2, part 3, part 4

To encrypt the content I will use the GetCert method that we did in part 4 of this series.

As with the signing part we will split this encryption into two bits. adding boundary to the content and encrypting part.

First the encrypting part:


public byte[] DoEncrypt(string message, X509Certificate2 encryptionCertificates)
{
byte[] messageBytes = Encoding.ASCII.GetBytes(message);

EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(messageBytes));

CmsRecipient recipients = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificates);

envelopedCms.Encrypt(recipients);

return envelopedCms.Encode();
}

With this function done we can now ready the content for encryptions. We add a simple boundary to the content and specifies what type the innner boundary is of. Important that if you skipped the signing part that you change this accordingly to match the type of you content.

Here is the code for encrypting and sending the mail:


public void encrypt(string content)
{
MailMessage message = new System.Net.Mail.MailMessage();
string encryptedContentType = "application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"";
string signatureBoundry2 = "--PTBoundry=3";
StringBuilder fullUnencryptedMessageBuilder = new StringBuilder();
fullUnencryptedMessageBuilder.Append("Content-Type: ");
fullUnencryptedMessageBuilder.Append("multipart/signed; ");
fullUnencryptedMessageBuilder.Append(" boundary=\"");
fullUnencryptedMessageBuilder.Append(signatureBoundry2);
fullUnencryptedMessageBuilder.Append("\"; protocol=\"application/x-pkcs7-signature\"; micalg=SHA1; ");

fullUnencryptedMessageBuilder.Append("\r\n");
fullUnencryptedMessageBuilder.Append("Content-Transfer-Encoding: ");
fullUnencryptedMessageBuilder.Append(TransferEncoding.SevenBit);
fullUnencryptedMessageBuilder.Append("\r\n\r\n");
fullUnencryptedMessageBuilder.Append(content);

string fullUnencryptedMessage = fullUnencryptedMessageBuilder.ToString();

byte[] encryptedBytes = DoEncrypt(fullUnencryptedMessage, GetCert());

MemoryStream stream = new MemoryStream(encryptedBytes);
AlternateView view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
message.AlternateViews.Add(view);
message.To.Add("youremail@yourdomain.com");

message.From = new MailAddress("someone@yourdomain.com");
message.Subject = "TEST";
SmtpClient smtp = new SmtpClient("smtp.yourdomain.com");
smtp.Send(message);

}

This function also sends out the mail you might wanna spilt this up to seperate methods. And do remember to give valide email adresses and a sane smtphost.

Now lets have a look at the result:

Yes there is a warning with the signature but rember in part 1 where did a selfsigned certificate this is the problem, but you cal always just accept the signature as trusted in your outlook.

Okay so how doesn’t the content that we build look like just before it is encrypted ?

If hightligthe the different steps we done in this series.

Also note the diffenrent boundary references from one part to underlaying content part.


Remember to change email smtp host and serial for certificat

Note you should implement all the explained methods in nice class’s that wraps all this functionality into one simple class. The code file you can download is constructed as a simple file so i would be easier to explain howto encrypt and sign emails. It is not intended to be used for production purposes.

Finished you now know ho to encrypt and sign mails with c#.

c# encrypting and signing mail

Categories: C# Tags: ,
  1. 1Siger1
    19/03/2012 at 14:03

    I checked your blog on your old address(istern.dk/blog/) and found there comments to this post. There was comment made by Muhammed. I need to achieve the same thing as Muhammed. I have tried the solution which you give to Muhammed, but without results. My target is to send email only signed and not encrypted, so the file in encryption should be smime.p7s. With your solution it will be smime.p7m – in the signature will be also whole message. Is there, a way to send only signature(smime.p7s)

  2. 1Siger1
    19/03/2012 at 15:13

    Hi,

    I see that was some time ago, but I searched “whole” internet and didn’t find anything usefull beyond your posts(I found also some other texts, but your was best written and with best examples).
    I found Pete Everett’s library some time ago. His lib has only options to encrypt or encrypt and sign(both use attachment “smime.p7m”). I need only to sign :((smime.p7s).
    My problem is also more difficult because I need also to validate signed emails (all types). I found solutions for both parts(sign and validate) with use of Microsoft CAPICOM lib, but my target is to use only mannaged code. Do you have any experience with validation of signed emails in .NET?

    Thanks for answer and help.
    Regards

  3. Ujwal
    16/11/2012 at 17:45

    Hi,

    With the help of your code I have put one feature in my app wherein user can send the encrypted digtialy signed mail.

    Scenario Description

    User login to the Application. Based on the login userid the application picks up the digital certificate (digital certificates are installed in web server with the machine account)

    Problem Description
    The recipient receives the message ‘Digital ID is not found by underlying system’. However the same recipient can open the encypted digitaly signed mail when the same user send any test mail in encrypted and digitaly signed through outlook.

    Please help

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: