0

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

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

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

他们的电子邮件回复:

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

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

到目前为止,还尝试了 3rd 方库 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);
    }
4

1 回答 1

1

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

首先,Convert.ToBase64String(arrayToEncode);不在 MIME 中根据需要换行。您需要使用的是带有Base64FormattingOptions.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 得到 Content-Transfer-Encoding 的base64.

我不确定将其添加为替代视图是否一定会起作用,我必须查看生成的 MIME 才能确定。

您可能会考虑使用我的开源库MimeKit来代替付费软件 IP*Works,它已经支持生成 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.
于 2014-04-16T22:33:17.003 回答