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

19. januar 2010 by Thomas Stern

Topic: How to encrypt and sign mail c#. Signed mail in c#, signing c#, c# send encrypted mail, signed encrypted mail c#, S/MIME messages,Sending encrypted email - C#

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:

 

 

mailbui5l

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.

 

mailbui34l

link to image

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

mailbuil2

you can find the code file for this project in the download section here is a link.

Rememer 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

7 comment(s) for “Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail)”

  1. Gravatar of Thomas Eldblom
    Thomas Eldblom Says:
    Could you please link to the other parts in your multi-part post?
  2. Gravatar of Thomas Stern
    Thomas Stern Says:
    They are there but the stylesheet was missing an entry to the a-tag. That has now been fixed.
  3. Gravatar of Muhammad
    Muhammad Says:
    if i want to send the mail till the part of signing only, what should i do ? please help?
  4. Gravatar of Thomas Stern
    Thomas Stern Says:
    @Muhammad if I get you right, you want to send an encrypted message to some that the can open with their private key ?
    In that case you need to have there public key and use that for encryption, and they should be able to open the mail with their private key.
    If you just want to sign and dont encrypt you always needs access to the private key otherwise you could impesonate other.
  5. Gravatar of Muhammad
    Muhammad Says:
    Thanks Thomas for your response.
    actually my question is about your code. i have a my own digital certificate with private key and public key and i will use private key to sign the message and verify the signature will be done by using public key, nice i understand that. but my question is about your code : if i want to use your code for only signing, which parts should i modify?!.
    your reponse is highly appreciated.
  6. Gravatar of Thomas Stern
    Thomas Stern Says:
    @Muhammed, No problem glad to help.
    I part 5 of this series I'm doing the encrypting part so you can leave out this part and settle for the first 4 parts. In part 5 there two functions
    DoEncrypt and Encrypt It should work without calling these two funcitons. I know this entire project could be build better but I really just wanted the information for this out there.
    Let me knwo how it worksout.
  7. Gravatar of Thomas Stern
    Thomas Stern Says:
    @Muhammed My fault use the encrypt function string and change from line 20 to 24 and use the variable fullUnencryptedMessage as input to view

    and try to remove the
    application/pkcs7-mime;

Leave comment: