S / Mime加密字符串

时间:2009-09-23 12:17:35

标签: c# encryption smime

我的任务是使用S / Mime加密来加密字符串。很久以前,我工作的公司为此购买了一个组件(来自IPWorks),但我们已经有无数的悲伤,让他们的组件在我们的服务器上很好地运行。不是功能问题,更多许可。

所以简而言之,我必须自己做。我已经搜索了MSDN和论坛,并将以下代码放在一起。不幸的是,它创造的输出并不是我所期望的。很多韩国人和特殊人物,我都不会期待。

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();
}

有人能看到明显的错误吗?

我与这段代码并没有“结婚”,所以如果你有另外的建议我可能会如何解决这个问题。

善良和感谢,

2 个答案:

答案 0 :(得分:1)

这一行是问题所在:

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;");

您正在将多个标头的值转储到Content-Type标头中。

相反,你想要的是更像这样的东西:

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;

那就是说,我正在开发一个比System.Net.Mail更好的MIME库。这个库名为MimeKit,我已经开始研究S / MIME支持。

答案 1 :(得分:0)

我认为StreamReader的默认编码器/解码器是UTF-8。如果在构造函数中将其更改为ASCII(最后一行)会发生什么?