dmoore1181
dmoore1181

Reputation: 2102

Email decryption in c#

I am using EWS to access an exchange 2013 server and gather emails from the inbox of that server. I need to be able to parse through the emails that are received at that box, which will include both encrypted and non encrypted emails. I have the .pfx file for decryption of the encrypted emails, but I am not sure of the proper way of encrypting these emails and have not found any good articles on google at this point. Can anyone assist?

Below is a sample of code that I am using (note that this is after reading lots of articles, so some stuff may not work together the way I think it should).

        var exchangeEmailHelper = new ExchangeEmailHelper();
        List<EmailMessage> = exchangeEmailHelper.getEmails();

        foreach (var email in emails)
        {
            string[] retValue = null;

            string[] mimeLines = Encoding.UTF8.GetString(email.MimeContent.Content).Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine("mimeLines has been read");
            //find out where the encoded message starts
            int ln;
            for (ln = 0; ln < mimeLines.Length; ln++)
            {
                if (mimeLines[ln] == "MIME-Version: 1.0") break;
            }
            Console.WriteLine($"There are {ln} lines until you get to the mime version.");

            StringBuilder sb = new StringBuilder(email.MimeContent.Content.Length);
            for (int sb1 = ln + 1; sb1 < mimeLines.Length; sb1++)
            {
                sb.Append(mimeLines[sb1]);
            }

            var y = Encoding.ASCII.GetBytes(sb.ToString());


            string test1 = Regex.Replace(email.MimeContent.ToString(), @"\t|\n|\r", "");
            test1 = test1.Substring(test1.IndexOf("Content-Transfer-Encoding: base64") + 33);

            var bytearray = Encoding.ASCII.GetBytes(test1);



            var collection = new X509Certificate2Collection();
            collection.Import(ConfigurationManager.AppSettings["certLocation"], ConfigurationManager.AppSettings["certPassword"], X509KeyStorageFlags.PersistKeySet);

            var certificate = collection[0];
            var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
            var data = privateKey.Decrypt(bytearray, false);

Upvotes: 2

Views: 1742

Answers (1)

jstedfast
jstedfast

Reputation: 38643

This would probably be a lot simpler if you used MimeKit:

MimeMessage message;

using (var stream = new MemoryStream (email.MimeContent.Content, email.MimeContent.Length))
    message = MimeMessage.Load (stream);

var pkcs7 = message.BodyParts.OfType<ApplicationPkcs7Mime> ().FirstOrDefault ();
if (pkcs7 != null) {
    using (var ctx = new TemporarySecureMimeContext ()) {
        using (var stream = File.OpenRead (ConfigurationManager.AppSettings["certLocation"]))
            ctx.Import (stream, ConfigurationManager.AppSettings["certPassword"]);

        // decrypt the MIME part (result will be another MIME entity)
        var decrypted = pkcs7.Decrypt (ctx);

        // The decrypted MIME entity could be a message/rfc822 part (which
        // contains a message), a multipart (such as multipart/mixed) which
        // contains a list of subparts, each with their own content... or it
        // could be a regular MIME part which just has content. Assuming it
        // is just a regular MIME part:
        if (decrypted is MimePart) {
            var part = (MimePart) decrypted;

            using (var stream = File.Create ("decrypted-content.dat"))
                part.Content.DecodeTo (stream);
        }
    }
}

Upvotes: 1

Related Questions