首页 > 解决方案 > 如何在带有附件的c#中加密和签名电子邮件

问题描述

我正在尝试发送带有附件的电子邮件,需要对其进行加密并签名。我可以对其进行加密,我可以对其进行签名,但是当我尝试同时执行这两种操作时,我会收到一封使用不可读文本签名的电子邮件,或者一封使用明文加密的电子邮件,没有 PJ,只有 base64 字符串。

感谢您的回答。这是我的代码以获得更好的答案:

string message = BuildMessage(body, pjs, false);
byte[] messageData = Encoding.UTF8.GetBytes(message);

SignedCms signedCms = new SignedCms(new ContentInfo(messageData));
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, GetCertificateFromEmailFrom(from));
signedCms.ComputeSignature(signer);

byte[] signedBytes = signedCms.Encode();
ContentInfo content = new ContentInfo(signedBytes);
EnvelopedCms envelopeCms = new EnvelopedCms(content);
CmsRecipientCollection toRecipientCollection = new CmsRecipientCollection();
Dictionary<string, X509Certificate2> certificatesForEncryption = new Dictionary<string, X509Certificate2>();
List<string> mailRefuser = GetCertificateFromEMailTo(to, out certificatesForEncryption);
foreach (KeyValuePair<string, X509Certificate2> certificate in certificatesForEncryption)
{
    CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate.Value);
    toRecipientCollection.Add(recipient);
}
envelopeCms.Encrypt(toRecipientCollection);
byte[] encryptedBytes = envelopeCms.Encode();

MailMessage msg = new MailMessage();
msg.From = new MailAddress(from);
foreach (string toMail in to)
{
    msg.To.Add(new MailAddress(toMail));
}
msg.Subject = subject;

MemoryStream ms = new MemoryStream(encryptedBytes);
AlternateView av = new AlternateView(ms, "application/pkcs7-mime; smime-type=enveloped-data"); //"application/pkcs7-mime; smime-type=signed-data;name=smime.p7m; content-transfer-encoding=utf-8; content-disposition=attachment; fileName=smime.p7m;");
msg.AlternateViews.Add(av);


SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["ServerSMTPWithCredentials"]);
smtpClient.Credentials = new NetworkCredential(login, password);
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certifficate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtpClient.EnableSsl = true;
smtpClient.Send(msg);

标签: c#emailencryptionsign

解决方案


我假设您正在使用 MimeKit(看起来像)。创建签名的 MultiPart 消息,对其进行加密并将其作为消息正文。

var ctx = new MimeKit.Cryptography.WindowsSecureMimeContext();
var signed = MultipartSigned.Create (ctx, signer, mimeMessage.Body);
var encrypted = ApplicationPkcs7Mime.Encrypt (ctx, toRecipientCollection, signed);
mimeMessage.Body = encrypted;

推荐阅读