签名/加密EDIFACT文档 - 格式错误 - C#

时间:2014-04-15 06:25:44

标签: c# email encryption mime edifact

我必须向政府机构发送EDI消息,该机构以特定方式签名/加密。

根据https://docs.google.com/document/d/1xOxsZG7nCXdd3ucFKJObheW4G6kFwflGFkzURS_haTY/edit?usp=sharing

我正在尝试此代码,但根据政府网关未正确格式化加密的S / MIME。

电子邮件回复:

我得到的错误代码是解密失败 您应该首先使用您的Gatekeeper证书签署您的EDI消息。 这会生成一个S / MIME blob。我们称之为“已签名”的S / MIME 然后,您使用已签名的blob并使用从我们的货物网站下载的海关网关证书对其进行加密 这会产生另一个S / MIME,我们称之为“加密的”S / MIME。

我正在使用正确的加密证书进行签名和加密。

到目前为止,还尝试过第三方库ActiveUp和Chilkat无济于事。

任何帮助解释海关规范并调整我可能出错的地方都非常感激。我已经在这个问题上工作了一个多星期。

    public static void SendEmail(string ediMsg, string clientCertificatePath,
        string clientCertificatePassword, string sender, string receiver, string subject, SmtpClient smtp,
        string customsCertificatePath)
    {
        //Load the certificate
        X509Certificate2 EncryptCert = new X509Certificate2(customsCertificatePath);

        X509Certificate2 SignCert =
           new X509Certificate2(clientCertificatePath, clientCertificatePassword);

        //Build the body into a string
        StringBuilder Message = new StringBuilder();

        ediMsg = "UNB+IATB:1+6XPPC+LHPPC+940101:0950+1' ...";

        /*The EDI document is first formatted as a MIME message [MIME], 
         * as the EDI Document may contain special characters, non-printable ASCII and binary data. */

        byte[] arrayToEncode = System.Text.Encoding.UTF8.GetBytes(ediMsg);
        ediMsg = Convert.ToBase64String(arrayToEncode);

        /*Within the MIME message, the Content-Transfer-Encoding header must be either “quoted-printable” 
         * or “base64”, and the Content-Type header should be set to “Application/EDIFACT”. */
        Message.AppendLine("Content-Type: Application/EDIFACT");
        Message.AppendLine("Content-Transfer-Encoding: base64");

        //The file name of the attachment for inbound e-mails (to Customs) must be the same as the Subject Line
        //(section 3.3) with the .edi suffix.
        Message.AppendLine("Content-Disposition: attachment; filename=\"" + subject + ".edi\"");

        /*I have tried this with 
         * (a) the raw ediMsg, 
         * (b) the base64 version of (a)
         * (c) quoted-printable version of (a)
         * (d) base64 version of (c)
         */ 
        Message.AppendLine(ediMsg);

        //Text must not be included in the body of the e-mail. EDI documents must be sent as an attachment.

        //Convert the body to bytes
        byte[] BodyBytes = Encoding.UTF8.GetBytes(Message.ToString());

        //sign
        var signedBytes = SignMsg(BodyBytes, SignCert);

        //Build the e-mail body bytes into a secure envelope
        EnvelopedCms Envelope = new EnvelopedCms(new ContentInfo(signedBytes));
        CmsRecipient Recipient = new CmsRecipient(
            SubjectIdentifierType.IssuerAndSerialNumber, EncryptCert);
        Envelope.Encrypt(Recipient);
        byte[] EncryptedBytes = Envelope.Encode();

        //Create the mail message
        MailMessage Msg = new MailMessage();
        Msg.To.Add(new MailAddress(receiver));
        Msg.From = new MailAddress(sender);
        Msg.Subject = subject;

        //Attach the encrypted body to the email as and ALTERNATE VIEW
        MemoryStream ms = new MemoryStream(EncryptedBytes);
        AlternateView av =
            new AlternateView(ms,
            "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
        Msg.AlternateViews.Add(av);

        //SmtpClient smtp = new SmtpClient(MailServer, 25);
        //send the email                                       
        smtp.Send(Msg);
    }

1 个答案:

答案 0 :(得分:1)

我不确定我要指出的问题是问题,但他们可能值得研究......

首先,Convert.ToBase64String(arrayToEncode);不会在MIME中根据需要换行。您需要使用的是this variantBase64FormattingOptions.InsertLineBreaks

其次,我不知道SignMsg()的作用,但请确保您还预先添加了正确的Content-Type,Content-Transfer-Encoding和(可能的)Content-Disposition标头。一旦您对数据进行了base64编码,Content-Type应为application/pkcs7-mime; smime-type=signed-data; name=smime.p7s,Content-Transfer-Encoding应为base64

第三,您为加密的外部部件提供的Content-Type标头是错误的。它应该是application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m

第四,确保加密数据获得base64编码,并且AlternativeView获得base64的内容传输编码。

我不确定将其作为替代视图添加是否必然有效,我必须看到生成的MIME以确定。

你可能会考虑使用的东西而不是IP *作为付费软件的作品是我的开源库名为MimeKit,它已经支持生成S / MIME消息。我还有一个名为MailKit的库,它支持你似乎正在使用的SMTP。

这两个库都可以通过NuGet轻松获得:MimeKitMailKit

你会做的是这样的事情:

// Note: if the email addresses do not match the certificates, you can
// use a SecureMailboxAddress instead, which allows you to specify the
// Fingerprint (aka Thumbprint) of the certificate to use for signing
// or encrypting.
var recipient = new MailboxAddress ("Receiver Name", "receiver@example.com");
var sender = new MailboxAddress ("Sender Name", "sender@example.com");

var message = new MimeMessage ();
message.To.Add (recipient);
message.From.Add (sender);
message.Subject = subject;

// create the application/edifact MIME part
var edifact = new MimePart ("application", "edifact");

// set the filename of the MIME part (adds a Content-Disposition header
// if not already present)
edifact.FileName = subject + ".edi";

// create the content stream of the MIME part
var content = new MemoryStream (Encoding.UTF8.GetBytes (ediMsg), false);

// set the content of the MIME part (we use ContentEncoding.Default because
// it is not encoded... yet)
edifact.ContentObject = new ContentObject (content, ContentEncoding.Default);

// encode the content using base64 *and* set the Content-Transfer-Encoding header
edifact.ContentTransferEncoding = ContentEncoding.Base64;

using (var ctx = new TemporarySecureMimeContext ()) {
    ctx.Import (clientCertificatePath, clientCertificatePassword);
    ctx.Import (customsCertificatePath);

    // sign and then encrypt the edifact part and then set the result as the
    // message body.
    message.Body = ApplicationPkcs7Mime.SignAndEncrypt (ctx, sender,
        DigestAlgorithm.Sha1, new [] { recipient }, edifact);
}

// MailKit's SMTP API is very similar to System.Net.Mail's SmtpClient API,
// so that shouldn't pose a problem.