S / Mime String Encryption

I was tasked with encrypting a string using S / Mime encryption. Eons ago, the company I work for bought a component for this (from IPWorks), but we had untold beams of grief and the component played well on our servers. No problem with functionality, more licenses.

So, I have to do it myself. I broke through MSDN and forums and put together the following code. Unfortunately, the result it produces is not what I expect. Lots of Korean and special characters I didn't expect.

public string EncryptString(string toEncrypt, string key)
{
// Convert the body to bytes
byte[] bodyBytes = Encoding.ASCII.GetBytes(toEncrypt);

// Encrypt the body
var envelopedCms = new EnvelopedCms(new ContentInfo(bodyBytes));

var certificate = new X509Certificate2(Encoding.ASCII.GetBytes(key));

var recipient = new CmsRecipient(certificate);
envelopedCms.Encrypt(recipient);
byte[] encryptedBytes = envelopedCms.Encode();
var msg = new MailMessage();
var ms = new MemoryStream(encryptedBytes);
var av = new AlternateView(ms, "application/pkcs7-mime; smime-type=enveloped-data;name=smime.p7m; content-transfer-encoding=Base64; content-disposition=attachment; fileName=smime.p7m;");
msg.AlternateViews.Add(av);

return new StreamReader(msg.AlternateViews[0].ContentStream).ReadToEnd();
}

      

Can anyone see an obvious error here?

I am not "married" to this code, so if you have an alternative suggestion on how I can do this please go through.

Kindness and gratitude,

Dan

+2


source to share


3 answers


Have you tried asking the evil Lord 52 for help? You can find it in a hollowed-out volcano all over the Nega Coast.



+2


source


This line is the problem:

var av = new AlternateView(ms, "application/pkcs7-mime; smime-type=enveloped-data;name=smime.p7m; content-transfer-encoding=Base64; content-disposition=attachment; fileName=smime.p7m;");

      

You are dumping the values โ€‹โ€‹of multiple headers into the Content-Type header.



Instead, you need something more:

var contentType = new ContentType ("application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m");
var attachment = new Attachment (ms, contentType);
attachment.ContentDisposition.FileName = "smime.p7m";
attachment.TransferEncoding = TransferEncoding.Base64;

      

However, I'm working on a much more advanced MIME library than System.Net.Mail (it's so poorly designed that it could only be designed for the complete amateur at Microsoft). This library is called MimeKit and I have already started working on S / MIME support.

+1


source


I think the default encoder / decoder for StreamReader is UTF-8. What happens if you change it to ASCII in the constructor (last line)?

0


source







All Articles