我想在不使用任何第三方API的情况下发送加密和签名的邮件。
如果我只发送带有签名的备用视图,Windows Mail可以验证它。如果我只发送带有加密数据的备用视图,Windows Mail可以解密它。但如果我发送两个,Windows Mail获得2个附件。如果我签署encryptedBytes
并将这些带符号的字节添加到备用视图中,它只验证签名并且消息为空。
有什么想法吗?
MailMessage message = new MailMessage();
message.From = new MailAddress(lblMail.Text);
message.Subject = txtSubject.Text;
string body = "Content-Type: text/plain\r\nContent-Transfer-Encoding: 7Bit\r\n\r\n" + structForm();
byte[] messageData = Encoding.ASCII.GetBytes(body);
ContentInfo content = new ContentInfo(messageData);
EnvelopedCms envelopedCms = new EnvelopedCms(content);
message.To.Add(new MailAddress(provMail));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, this.certificate);
envelopedCms.Encrypt(recipient);
byte[] encryptedBytes = envelopedCms.Encode();
SignedCms Cms = new SignedCms(new ContentInfo(encryptedBytes));
CmsSigner Signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, new X509Certificate2(@"c:\serv.pfx","123"));
Cms.ComputeSignature(Signer);
byte[] SignedBytes = Cms.Encode();
MemoryStream encryptedStream = new MemoryStream(encryptedBytes);
AlternateView encryptedView = new AlternateView(encryptedStream, "application/pkcs7-mime; smime-type=signed--data;name=smime.p7m");
message.AlternateViews.Add(encryptedView);
MemoryStream signedStream = new MemoryStream(SignedBytes);
AlternateView signedView = new AlternateView(signedStream, "application/pkcs7-mime; smime-type=signed-data;name=sig.p7m");
message.AlternateViews.Add(signedView);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("emailaddress@xpto.com", "XXXXXX");
SmtpClient client = new SmtpClient("smtp.xpto.com");
client.UseDefaultCredentials = false;
client.Credentials = SMTPUserInfo;
client.Send(message);
Label2.Text = "Assinado e cifrado!";
答案 0 :(得分:3)
您应首先签名,然后加密。
虽然原始的CMS和S / MIME规范允许您按任意顺序执行操作,但后来的工作指出,签署一个您无法阅读的文档是一个非常糟糕的主意。签名应该在纯文本上。
生成的MIME消息应该只有一个部分,应该是S / MIME封装数据。您的邮件有两部分,加密部分标有错误标记的签名数据内容类型。创建并签署SignedCms
对象。对其进行编码,并使用编码值作为EnvelopedCms
对象的内容。加密,并使用其编码值作为MailMessage
的内容,内容类型为“application / pkcs7-mime; smime-type = enveloped-data”。