I am using Mime kit for send mail and encryption. The code is,
public void SendMail(string filePath)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test", "[email protected]"));
message.To.Add(new MailboxAddress("Test Mail", "[email protected]"));
message.To.Add(new MailboxAddress("Test", "[email protected]"));
message.Subject = "TEST: ";
var subject = "TEST:";
var body = new TextPart("plain")
{
Text = "Sample comments"
};
var attachment = new MimeKit.MimePart("multipart/related", "txt")
{
Content = new MimeContent(File.OpenRead(filePath), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName(filePath)
};
var multipart = new Multipart("mixed");
multipart.Add(body);
multipart.Add(attachment);
message.Body = multipart;
var certificateFile = @"E:\RESDE_RSA.pfx";
var certificate = new X509Certificate2(certificateFile,"", X509KeyStorageFlags.Exportable);
var recipientCollection = new CmsRecipientCollection();
var bountyRecipientCertificate = DotNetUtilities.FromX509Certificate(certificate);
var recipient = new CmsRecipient(bountyRecipientCertificate);
recipient.EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.Aes256 };
recipientCollection.Add(recipient);
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect("smtp.gmail.com", 25, false);
client.Authenticate("[email protected]", "password");
client.Send(message);
client.Disconnect(true);
}
}
The mail is sending successfully, but the encryption and signed of message not correct. I didn't get any solution for how to decrypt and signed the message. I am working in an MVC application.
Firstly, this is incorrect:
var attachment = new MimeKit.MimePart("multipart/related", "txt")
That will result in:
Content-Type: multipart/related/txt
That is a completely wrong mime-type.
Not sure what you are going for, but it definitely should not be a multipart
anything.
Now to your main question regarding why your message isn't being encrypted.
Easy: you are doing the first few steps of getting a list of CMS recipients (which looks ok), but you aren't doing anything with them.
var certificateFile = @"E:\RESDE_RSA.pfx";
var certificate = new X509Certificate2(certificateFile,"", X509KeyStorageFlags.Exportable);
var recipientCollection = new CmsRecipientCollection();
var bountyRecipientCertificate = DotNetUtilities.FromX509Certificate(certificate);
var recipient = new CmsRecipient(bountyRecipientCertificate);
recipient.EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.Aes256 };
recipientCollection.Add(recipient);
// now you need to actually encrypt
using (var ctx = new TemporarySecureMimeContext ()) {
var encrypted = ApplicationPkcs7Mime.Encrypt (ctx, recipientCollection, multipart);
message.Body = encrypted;
}