Search code examples
c#x509certificatex509certificate2

How to create a minimal dummy X509Certificate2?


I'm unit testing a .NET application; some of the unit tests involve programmatically generating X509Certificate2 objects.

I don't care about actual signing/private key/validation stuff, I'd just like to have an object that doesn't throw exceptions when its fields are examined. I tried using the parameterless constructor, but then a whole bunch of fields throw exceptions when accessed. As seen in the debugger:

SubjectName = '(new System.Collections.Generic.Mscorlib_CollectionDebugView(result.Certificates)).Items[0].SubjectName' threw an exception of type 'System.Security.Cryptography.CryptographicException'

I also tried passing a byte array with some random numbers in it, but that didn't even construct (does the array need to be a specific size?)

So, question: what is the simplest (fewest lines of code) way to programmatically generate an X509Certificate2 object which will not throw exceptions upon field/property accesses?


Solution

  • I would suggest the following:

    1. Generate a certificate using makecert.
    2. Add the certificate to your project and change its Build Action to Embedded Resource.
    3. Load the certificate from the resource in your unit test setup, see below.

    Code:

    byte[] embeddedCert;
    Assembly thisAssembly = Assembly.GetAssembly(typeof(MyType));
    using (Stream certStream = thisAssembly.GetManifestResourceStream("YourProjectName.localhost.pfx"))
    {
      embeddedCert = new byte[certStream.Length];
      certStream.Read(embeddedCert, 0, (int)certStream.Length);
    }
    
    _signingCert = new X509Certificate2(embeddedCert, "password");
    

    At this point you should be good to go as far as interacting with the certificate. You can create different variants if your unit tests have different needs.