How to create a minimal dummy X509Certificate2?

前端 未结 4 1947
暖寄归人
暖寄归人 2021-01-01 11:29

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

4条回答
  •  情深已故
    2021-01-01 12:23

    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.

提交回复
热议问题