Search code examples
c#smimeopenpop

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


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?


Solution

  • 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.