c# - 如何在带有附件的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);
解决方案
我假设您正在使用 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;
推荐阅读
- java - Java同步计数器相同的值由不同的线程打印
- clickhouse - 使用 ClickHouse 折叠重叠的时间间隔
- javascript - 如何检查php数组值是否在js数组中?
- python - 为什么colliderect没有检测到我的碰撞
- r - LRtest - 拆分向量不允许 NA
- javascript - 我如何运行这个函数,我想在输入中提供数据,然后将它传递给函数,所以我做得正确吗?
- powershell - 如何从 venv 中运行 powershell 脚本?
- java - 正确实现从字符串变量中的给定 URL 下载 HTML 源代码的说明
- linux - 如何从ip中提取前2个数字
- python - 如何为训练 ML 或 DL 算法创建用于可视化损失图的动画?