带有附件的数字签名电子邮件



我有一个mailer脚本,它发送一封数字签名的电子邮件。现在我必须把文件附在邮件上。我的问题:

  1. 如果没有附件,则邮件是正常的,并且经过了数字签名。这没问题
  2. 如果有任何附件,则表示邮件正文丢失且未签名,但它会正确发送文件。为什么会发生这种情况

mailer(to, from, from_name, relay, subject, body, attachment_list);

private void mailer(string toaddress, string fromaddress, string fromaddress_disp, string relays, string mailsubject, string bodytext, List<string> att)
{
    string certname = "";
    MailAddress from = new MailAddress(fromaddress, fromaddress_disp);
    MailAddress to = new MailAddress(toaddress);
    MailMessage message = new MailMessage(from, to);
    //this is the attachment part added
    if (att.Count != 0)
        {
            for (int i = 0; i < att.Count; i++)
            {
                Attachment attachment = new Attachment(att[i].ToString());
                message.Attachments.Add(attachment);
            }
        }
    //this is the end of attachment part added
    message.Subject = mailsubject;
    message.IsBodyHtml = true;
    string body = "Content-Type: text/html; charset=iso-8859-1 rnContent-Transfer-Encoding: 8bitrnrn" + bodytext;
    byte[] messageData = Encoding.ASCII.GetBytes(body);
    ContentInfo content = new ContentInfo(messageData);
    SignedCms Cms = new SignedCms(new ContentInfo(messageData));
    X509Store store = new X509Store(StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    RSACryptoServiceProvider csp = null;
    X509Certificate2Collection certCollection = store.Certificates;
    X509Certificate2 cert = null;
    foreach (X509Certificate2 c in certCollection)
    {
        if ((c.Subject.Contains("myEmailAddress")) && (c.FriendlyName.Contains("CompanyEmailDigSig")))
        {
            cert = c;
            break;
        }
    }
    if (cert != null)
    {
            csp = (RSACryptoServiceProvider)cert.PrivateKey;
    }
    else
    {
        throw new Exception("Valid certificate was not found");
    }
    CmsSigner Signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
    Cms.ComputeSignature(Signer);
    byte[] SignedBytes = Cms.Encode();
    MemoryStream signedStream = new MemoryStream(SignedBytes);
    AlternateView signedView = new AlternateView(signedStream, "application/pkcs7-mime; smime-type=signed-data; name=sig.p7m");
    message.AlternateViews.Add(signedView);
    SmtpClient client = new SmtpClient(relays);
    store.Close();
    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
    //exception
    }
}

问题是它只签署了正文:

byte[] messageData = Encoding.ASCII.GetBytes(body);
ContentInfo content = new ContentInfo(messageData);
SignedCms Cms = new SignedCms(new ContentInfo(messageData));

如何签署整个邮件?

我终于可以用EASendMail:解决这个问题了

http://www.emailarchitect.net/easendmail/dev/csharp.asp

此代码对整个电子邮件消息以及任何附件和/或嵌入的图像进行签名。它也很容易使用。

相关内容

  • 没有找到相关文章

最新更新