簡體   English   中英

如何在帶有附件的C#中加密和簽名電子郵件

[英]How to encrypt and signed an email in c# with attachment

我正在嘗試發送帶有附件的電子郵件,並且需要對其加密並對其進行簽名。 我可以對其進行加密,也可以對其進行簽名,但是當我嘗試同時執行這兩項操作時,我會收到一封包含不可讀文本的電子郵件簽名,或者一封包含明文的電子郵件加密,而沒有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);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM