1

I'm working with mimekit to encrypt and decrypt mime messages and I'm encountering this error everytime I try to decrypt a message:

Unexpected object reading content. BouncyCastle.Crypto at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in //crypto/src/cms/CMSContentInfoParser.cs:line 35 at Org.BouncyCastle.Cms.CmsEnvelopedDataParser..ctor(Stream envelopedData) in //crypto/src/cms/CMSEnvelopedDataParser.cs:line 65 at MimeKit.Cryptography.BouncyCastleSecureMimeContext.d__50.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__11.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 302 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at PasarelaLibrary.Bases.GraphService.BaseGraphPasarela.d__9.MoveNext() in C:\Dev\Euroval\PasarelaAceuro\PasarelaLibrary\Bases\GraphService\BaseGraphPasarela.cs:line 237

Inner exception

Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1SequenceParser'. at Org.BouncyCastle.Cms.CmsContentInfoParser..ctor(Stream data) in /_/crypto/src/cms/CMSContentInfoParser.cs:line 27

the problem is I'm just trying to encrypt and decrypt a message to test the library and the flow of the application and I'm getting this error. Above you can find the code I'm using. I'm using a x509Certificate with a password that I'm importing in the TemporarySecureMimeContext.

using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;
var dec = await context.DecryptAsync(testencrypted); //here it explodes :(

public static async Task<MimeMessage> GetEncryptedMessage(TemporarySecureMimeContext context, Stream stream, string subject, X509Certificate certificate, string mailFrom, string mailTo)
{
    stream.Position = 0;
    SecureMailboxAddress mailFromEncrypted = new SecureMailboxAddress("name", mailFrom, certificate.GetFingerprint());
    SecureMailboxAddress mailToEncrypted = new SecureMailboxAddress("name", mailTo, certificate.GetFingerprint());
    BodyBuilder bodyBuilder = new BodyBuilder();
    using StreamReader reader = new StreamReader(stream);
    bodyBuilder.TextBody = await reader.ReadToEndAsync();
    MimeMessage message = new MimeMessage(new List<InternetAddress> { mailFromEncrypted }, new List<InternetAddress> { mailToEncrypted }, subject, bodyBuilder.ToMessageBody());
    message.Date = DateTime.Now;
    message.MessageId = MimeUtils.GenerateMessageId();
    await message.EncryptAsync(context);
    return message;
}

I already read other posts here and in other forums but nothing worked for this case scenario. Could someone help me with this?

1 Answers1

1

You're using it wrong :-)

You are trying to decrypt a MIME message stream. You can't do that.

The SecureMimeContext.Decrypt() and DecryptAsync() methods expect the encrypted content of the MIME message.

If your goal is to load the MimeMessage and decrypt it, you would change your code to this:

using var context = new TemporarySecureMimeContext();
await context.ImportAsync(certificate);

// get an encrypted message
var encryptedMessage = await GetEncryptedMessage(context, stream, fileroute, certificate, mailFrom, mailTo);

// write the encrypted message to a stream
using var testencrypted = new MemoryStream();
await encryptedMessage.WriteToAsync(testencrypted);
testencrypted.Position = 0;

// load the message from the stream
var loadedMessage = await MimeMessage.LoadAsync(testencrypted);

// get the encrypted body
var encryptedBody = (ApplicationPkcs7Mime) loadedMessage.Body;

// decrypt it
var decryptedBody = await encryptedBody.DecryptAsync(context);

// restore the message to the pre-encrypted state
loadedMessage.Body = decryptedBody;
jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • Hello! Thanks for your fast answer. I was wondering why you are using the x509Certificate class from the BouncyCastle namespace instead of System.Security.Cryptography.X509Certificates.X509Certificate2 taking in count this class has some improvements over the BouncyCastle one, as for example an accessor for the private key. Right now I'm having an exception that says "no suitable private key was found" in the moment I try to decrypt the message, but I'm pretty sure this certificate is valid. Could you help me with that again? – victor garcia exposito Feb 11 '22 at 07:29
  • 1
    You can use the WindowsSecureMimeContext if you want to use System.Security’s X509Certificates. MimeKit uses BouncyCastle so it works on Mac/Linux running on Mono. – jstedfast Feb 11 '22 at 11:30
  • Post a new question regarding your PrivateKeyNotFoundException issue, but it probably means you haven’t added the private key to the context you are using. – jstedfast Feb 11 '22 at 11:32
  • I want to upvote your answer but I can't because I'm a newbie here :( That solved my problem but I think now I'm having trouble sending the email via Graph API, when I get the message from that API and I try to decrypt it I get the following error: "ASN1 bad tag value met" It seems that this comes from the Microsoft CmsEnveloped class that gets called from behind so I suppose I should post another thread about it. Anyway thanks a lot! – victor garcia exposito Feb 14 '22 at 13:07
  • No problem. You might not be able to upvote it, but you should be able to accept it – jstedfast Feb 14 '22 at 13:22
  • do you still want me to post another thread about the PrivateKeyNotFoundException issue? – victor garcia exposito Feb 14 '22 at 13:23
  • If you still need help with it, yes – jstedfast Feb 14 '22 at 13:23
  • Well, now it's not a problem related to that as I'm able to encrypt and decrypt the message I generate in code but if I send the encrypted message via Graph API and then try to retrieve it I get the error ASN1 bad tag value met. I read somewhere else that Graph API doesn't have full suport for MIME messages but anyway I thought I could use it anyway with MimeKit as you can get the message as a stream with all the data according to this documentation: https://docs.microsoft.com/es-es/graph/outlook-get-mime-message I think you have nothing to do with it but some guidance would be appreciated – victor garcia exposito Feb 14 '22 at 13:28
  • I'd have to see your code to know what the issue is. – jstedfast Feb 14 '22 at 15:48
  • Ok, I'll create another post, thanks a lot! – victor garcia exposito Feb 14 '22 at 15:57