Howto Verify Signature of a SMIME multipart/signed application/x-pkcs7-signature Mail

一世执手 提交于 2019-12-12 06:06:33

问题


I am working on a larger application which receives email by POP3, IMAP or through import from .msg Files (Exported form Outlook or dragged over from Outlook).

Recently I received an email with an attachment "smime.p7m". After further inspection it turned out to be a MIME Message with

Content-Type: multipart/signed; protocol="application/x-pkcs7-signature";

Among other parts it contains one section

Content-Type: application/x-pkcs7-signature; name="smime.p7s" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="smime.p7s"

I tried to verify this signature using OpenPop as a MIME Message Parser and SignedCms to check the signature. My attempt looks like this:

var datapart = OpenPop.MessagePart[...];
var part3 = OpenPop.MessagePart[3]; // the signature

var ci = new ContentInfo(datapart);            
var sCMS = new SignedCms(ci, detached: true);
sCMS.Decode(part3.Body);
sCMS.CheckHash();

sCMS.CheckSignature(verifySignatureOnly:true);

But no matter what I use for datapart I always get

System.Security.Cryptography.CryptographicException The hash value is not correct.

How can I verify the signature?

Are there better approaches?


回答1:


The easiest way for you to do this would be to use MimeKit (which is not only open source but also free for commercial use).

Since all you care about is verifying the signatures, you could just use a MimeKit.Cryptography.TemporarySecureMimeContext instead of setting up your own (like the README and other documentation talks about doing).

Typically, when you receive a message signed via S/MIME, it is almost always the root-level MIME part that is the multipart/signed part, which makes this somewhat easier (the first step toward verifying signatures is to locate the multipart/signed part).

var signed = message.Body as MultipartSigned;
if (signed != null) {
    using (var ctx = new TemporaryMimeContext ()) {
        foreach (var signature in signed.Verify (ctx)) {
            try {
                bool valid = signature.Verify ();

                // If valid is true, then it signifies that the signed
                // content has not been modified since this particular
                // signer signed the content.
                //
                // However, if it is false, then it indicates that the
                // signed content has
                // been modified.
            } catch (DigitalSignatureVerifyException) {
                // There was an error verifying the signature.
            }
        }
    }
}

You can find API documentation for MimeKit at www.mimekit.net/docs.



来源:https://stackoverflow.com/questions/31183481/howto-verify-signature-of-a-smime-multipart-signed-application-x-pkcs7-signature

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!