I have been tasked with encrypting a string using S/Mime encryption. Eons ago, the firm I work for bought a component for this (from IPWorks) but we have had untold bundles of grief getting their component to play nicely on our servers. Not a functionality issue, more licensing.
So in short, I must do it myself. I have trawled the MSDN and forums and put together the following code. Unfortunately the output it creates is not what I expect. Lots of Korean and special characters that I would not 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 blunder here?
I am not "married" to this code so if you have an alternate suggestion to how I might do this fire away.
Kindness and thanks,
Dan