Unable to decrypt p7m using MimeKit

2019-07-31 17:33发布

I have located my smime.p7m from my email message, I read it as stream and try to decrypt it using MimeKit, but it failed with Operation is not valid due to the current state of the object.

using (MemoryStream ms = new MemoryStream(data)) {
    CryptographyContext.Register(typeof(WindowsSecureMimeContext));
    ApplicationPkcs7Mime p7m = new ApplicationPkcs7Mime(SecureMimeType.EnvelopedData, ms);
    var ctx = new WindowsSecureMimeContext(StoreLocation.CurrentUser);
    p7m.Verify(ctx, out MimeEntity output);
}

Following the example on https://github.com/jstedfast/MimeKit doesn't help either. Anyone familiar with MimeKit could chime in?

EDIT:

After decrypting the p7m, am I supposed to use the MimeParser to parse the content? I got the following from the decryption:

Content-Type: application/x-pkcs7-mime; name=smime.p7m; smime-type=signed-data
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m

MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAaCAJIAEWUNvbnRl
bnQtVHlwZTogdGV4dC9wbGFpbjsNCgljaGFyc2V0PSJ1cy1hc2NpaSINCkNvbnRlbnQtVHJhbnNm
ZXItRW5jb2Rpbmc6IDdiaXQNCg0KdGVzdA0KAAAAAAAAoIImTTCCBaIwggOKoAMCAQICBguC3JQz
...more...

But when parsing with MimeParser,

System.FormatException: Failed to parse message headers.
   at MimeKit.MimeParser.ParseMessage(Byte* inbuf, CancellationToken cancellationToken)
   at MimeKit.MimeParser.ParseMessage(CancellationToken cancellationToken)

UPDATE:

Ah, so it turns, calling Decrypt only gives me the SignedData, I need to then call Verify to pull the original data... this is kind of misleading, I thought Verify would simply verify it... which is why I didn't bother calling it, since I don't really need to verify it... Perhaps it should be call Decode instead? That's what I was trying to do originally, ((MimePart) signedData).Content.DecodeTo(...).

So in the end, I had to do something like this to extract the data.

CryptographyContext.Register(typeof(WindowsSecureMimeContext));
ApplicationPkcs7Mime p7m = new ApplicationPkcs7Mime(SecureMimeType.EnvelopedData, ms);
var ctx = new WindowsSecureMimeContext(StoreLocation.CurrentUser);

if (p7m != null && p7m.SecureMimeType == SecureMimeType.EnvelopedData)
{
    // the top-level MIME part of the message is encrypted using S/MIME
    p7m = p7m.Decrypt() as ApplicationPkcs7Mime;
}


if (p7m != null && p7m.SecureMimeType == SecureMimeType.SignedData)
{
    p7m.Verify(out MimeEntity original);    // THE REAL DECRYPTED DATA
    using (MemoryStream dump = new MemoryStream())
    {
        original.WriteTo(dump);
        decrypted = dump.GetBuffer();
    }
}

1条回答
聊天终结者
2楼-- · 2019-07-31 18:10

You are getting an InvalidOperationException because you are calling Verify() on a EncryptedData.

You need to call Decrypt().

Verify() is for SignedData.

查看更多
登录 后发表回答