Search code examples
c#mimesmimemimekit

MimeKit - Need help loading pfx file: NullReferenceException


I'm new to C# and mimekit and trying to do the basic S/MIME setup from MimeKits github README. Trying to load a pfx file to decrypt S/MIME messages. My code:

    public void LoadFile(string filename)
    {
        this.Message = MimeMessage.Load(filename);
        Console.WriteLine($"Loaded {filename}.");
        CryptographyContext.Register(typeof(MySecureMimeContext));
        using (var ctx = new MySecureMimeContext())
        {
            using (var stream = File.OpenRead("/path/to/keyStore.p12"))
            {
                ctx.Import(stream, "testas2");
            }
        }
    }

And heres the secure mime context file:

using System.IO;
using System.Data.SQLite;
using MimeKit.Cryptography;

namespace dotnet_smime
{
class MySecureMimeContext : DefaultSecureMimeContext
{
    public MySecureMimeContext() : base(OpenDatabase("certdb.sqlite"))
    {
    }

    static IX509CertificateDatabase OpenDatabase(string fileName)
    {
        var builder = new SQLiteConnectionStringBuilder();
        builder.DateTimeFormat = SQLiteDateFormats.Ticks;
        builder.DataSource = fileName;

        if (!File.Exists(fileName))
            SQLiteConnection.CreateFile(fileName);

        var sqlite = new SQLiteConnection(builder.ConnectionString);
        sqlite.Open();

        return new SqliteCertificateDatabase(sqlite, "password");
    }
}
}

When the code calls ctx.Import(...), i get this:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at MimeKit.Cryptography.BouncyCastleCertificateExtensions.AsHex(Byte[] blob)
   at MimeKit.Cryptography.X509CertificateDatabase.GetValue(X509CertificateRecord record, String columnName)
   at MimeKit.Cryptography.SqlCertificateDatabase.GetInsertCommand(X509CertificateRecord record)
   at MimeKit.Cryptography.X509CertificateDatabase.Add(X509CertificateRecord record)
   at MimeKit.Cryptography.DefaultSecureMimeContext.Import(Stream stream, String password)
   at dotnet_smime.MimePkcs7.LoadFile(String filename) in /Users/sakwaalvitre/projects/edi/dotnet-smime/MimePkcs7.cs:line 27
   at dotnet_smime.Program.Main(String[] args) in /Users/sakwaalvitre/projects/edi/dotnet-smime/Program.cs:line 19

From what i can tell, ctx and stream are both defined and stream has data.

Thanks in advance!


Solution

  • This is a bug in MimeKit 2.5.2 that happens when a certificate has a null SubjectKeyIdentifier.

    Try out the nuget from https://www.myget.org/feed/mimekit/package/nuget/MimeKit

    I just made a fix and the 2.5.2.16 build should contain the fix for this.

    If it doesn't work, let me know.