解密mime内容时出错-满足ASN1错误的标签值

时间:2018-12-20 15:30:07

标签: c# mimekit

我编写了一个函数来创建mime消息,并使用存储在证书存储区中的用户公共证书对内容加密,而私钥存储在我的智能卡上。我的功能只是将pkcs7mime内容保存到文件中。 我还有另一个测试功能,它只是读取文件并尝试解密内容。但是,当我尝试解密时,出现错误:满足ASN1错误标签值。

我的加密功能代码:

private static void EncryptMime()
    {
        MimeMessage mm = new MimeMessage();
        var ctx = new WindowsSecureMimeContext();
        mm.From.Add(new MailboxAddress("Bob", "Bob@diamondsg.onmicrosoft.com"));
        mm.To.Add(new MailboxAddress("Alice", "Alice@diamondsg.onmicrosoft.com"));

        mm.Subject = "Smime Test";

        mm.Body = new TextPart("plain")
        {
            Text = @"This is a test."
        };

        var signer = mm.From.Mailboxes.FirstOrDefault();
        var recipients = mm.To.Mailboxes.AsEnumerable();
        ApplicationPkcs7Mime p7m = ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, DigestAlgorithm.Sha1, recipients, mm.Body);

        MemoryStream ms = new MemoryStream();
        p7m.WriteTo(ms, true);
        byte[] bytes = ms.GetBuffer();
        File.WriteAllBytes("smime.p7m", bytes);
    }

这是我的解密功能:

private static void DecryptMime()
    {

        CryptographyContext.Register(typeof(WindowsSecureMimeContext));

        string messagetext = "";
        // Read the p7m file           
        byte[] bytes = 
        File.ReadAllBytes("smime.p7m");
        MemoryStream ms = new MemoryStream(bytes);
        ApplicationPkcs7Mime p7m = new ApplicationPkcs7Mime(SecureMimeType.EnvelopedData, ms);
        // WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(StoreLocation.CurrentUser);

        if (p7m != null && p7m.SecureMimeType == SecureMimeType.EnvelopedData)
        {
            Console.WriteLine("Decrypting message...");
            try
            {
                p7m = p7m.Decrypt() as ApplicationPkcs7Mime;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error decrypting: " + ex.Message);
            }
        }

        if (p7m != null && p7m.SecureMimeType == SecureMimeType.CompressedData)
        {
            Console.WriteLine("Decompressing message...");
            p7m = p7m.Decompress() as ApplicationPkcs7Mime;
        }

        if (p7m != null && p7m.SecureMimeType == SecureMimeType.SignedData)
        {
            Console.WriteLine("Verifying message...");
            p7m.Verify(out MimeEntity entity);
            MimeMessage mm = new MimeMessage(entity);
            messagetext = mm.GetTextBody(MimeKit.Text.TextFormat.Text);
            Console.WriteLine("Decrypted Message: " + messagetext);
        }           
    }

编辑: 我尝试使用以下代码来隔离问题:

MemoryStream ms = new MemoryStream();
        p7m.WriteTo(ms);    
ApplicationPkcs7Mime new_p7m = new ApplicationPkcs7Mime(SecureMimeType.EnvelopedData, ms);  

        if (new_p7m != null && new_p7m.SecureMimeType == SecureMimeType.EnvelopedData)
        {
            Console.WriteLine("Decrypting message...");
            try
            {
                new_p7m = new_p7m.Decrypt() as ApplicationPkcs7Mime;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error decrypting: " + ex.Message);
            }
        }

所以问题似乎早于WriteTo()函数开始...

更新#2: 好的,所以我在p7m和new_p7m对象上都做了一个toString。显然,内容有所不同...

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

MIIOOwYJKoZIhvcNAQcDoIIOLDCCDigCAQIxggEwMIIBLAIBAoAU2NQqDvYHJuMeC27IpyiV
....

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

Q29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9wa2NzNy1taW1lOyBzbWltZS10eXBlPWVudmVs
....

实际上,实际内容正在发生变化...非常奇怪...

1 个答案:

答案 0 :(得分:0)

我敢打赌,您将内容保存到磁盘的代码正在写入损坏的文件:

MemoryStream ms = new MemoryStream();
p7m.WriteTo(ms, true);
byte[] bytes = ms.GetBuffer();
File.WriteAllBytes("smime.p7m", bytes);

上述代码的问题在于,在大多数情况下,GetBuffer()返回的字节数多于内存流实际使用的字节数。上面的逻辑还将内容保存在base64中,这可能不是您想要的。以下代码段会将base64内容解码为smime.p7m文件:

using (var stream = File.Create ("smime.p7m"))
    p7m.Content.DecodeTo (stream);

然后,要重新构造MIME部分以进行解密,请执行以下操作:

var bytes = File.ReadAllBytes ("smime.p7m");
var ms = new MemoryStream (bytes);
var p7m = new ApplicationPkcs7Mime (SecureMimeType.EnvelopedData, ms);

您面临的问题是内容以前是base64编码的,应该没有。

当然,除非确实需要仅保存原始内容,然后以困难的方式重新构建application / pkcs7-mime部分,否则为什么不这样保存整个MIME部分呢?

using (var stream = File.Create ("smime.p7m"))
    p7m.WriteTo (stream);

然后像这样重新加载它:

using (var stream = File.OpenRead ("smime.p7m"))
    p7m = (ApplicationPkcs7Mime) MimeEntity.Load (stream);

那么您不必担心会出错。