S / mime签名并加密电子邮件,在附件末尾添加签名

时间:2017-11-08 14:29:20

标签: c# smime

附加到电子邮件的文本文件会收到附加字符,我认为这是签名,电子邮件客户端表示电子邮件未签名。

我是否应该使用AlternativeView进行签名和加密?我搞砸了内容类型吗?

从各种例子来看,这是我到目前为止所提出的:

var buffer = new StringBuilder();
buffer.Append("MIME-Version: 1.0\r\n");
buffer.Append("Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n");
buffer.Append("\r\n");
buffer.Append("This is a multi-part message in MIME format.\r\n");
buffer.Append("--unique-boundary-1\r\n");
buffer.Append("Content-Type: text/plain\r\n");  
buffer.Append("Content-Transfer-Encoding: 7Bit\r\n\r\n");
buffer.Append(bodyText);
if (!bodyText.EndsWith("\r\n"))
    buffer.Append("\r\n");
buffer.Append("\r\n\r\n");

buffer.Append("--unique-boundary-1\r\n");
buffer.Append("Content-Type: application/octet-stream; file=" + outputFileName + "\r\n");
buffer.Append("Content-Transfer-Encoding: base64\r\n");
buffer.Append("Content-Disposition: attachment; filename=" + outputFileName + "\r\n");
buffer.Append("\r\n");

var memoryStream = new MemoryStream();
var writer = new StreamWriter(memoryStream);
writer.Write(_exportString);
writer.Flush();
writer.Dispose();

var binaryData = memoryStream.ToArray();

var base64Value = Convert.ToBase64String(binaryData, 0, binaryData.Length);
var position = 0;
while (position < base64Value.Length)
{
    var chunkSize = 100;
    if (base64Value.Length - (position + chunkSize) < 0)
        chunkSize = base64Value.Length - position;
    buffer.Append(base64Value.Substring(position, chunkSize));
    buffer.Append("\r\n");
    position += chunkSize;
}
buffer.Append("\r\n");

var body = buffer.ToString();

var messageData = Encoding.ASCII.GetBytes(body);

//add digital signature:
var signedCms = new SignedCms(new ContentInfo(messageData));
var signerCertificate = GetOurCertificate();
var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCertificate);
signedCms.ComputeSignature(signer);
var signedBytes = signedCms.Encode();
////

//Encrypt
var content = new ContentInfo(signedBytes);
var envelopedCms = new EnvelopedCms(content);

message.To.Add(new MailAddress("yyy@xxx.com"));
var recipientCertifcate = GetCertificate("C544FD2E80BD2B3994D43DBDB820DBE3A3A29922");
var recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, recipientCertifcate );

envelopedCms.Encrypt(recipient);
var encryptedBytes = envelopedCms.Encode();
////

var stream = new MemoryStream(encryptedBytes);
var view = new AlternateView(stream, "application/pkcs7-mime; smime-type=enveloped-data;name=smime.p7m");
message.AlternateViews.Add(view);


SmtpClient mailClient = new SmtpClient("localhost", 25);
mailClient.Send(message);

0 个答案:

没有答案