如何在带有附件的C#中加密和签名电子邮件

时间:2018-09-21 13:14:38

标签: c# email encryption sign

我正在尝试发送带有附件的电子邮件,并且需要对其进行加密和签名。 我可以对其进行加密,也可以对其进行签名,但是当我尝试同时执行这两种操作时,都会收到一封包含不可读文本的电子邮件签名,或者一封包含明文的电子邮件加密,而没有PJ仅base64string。

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

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

1 个答案:

答案 0 :(得分:0)

我假设您正在使用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;