如何创建一个最小的虚拟X509Certificate2? [英] How to create a minimal dummy X509Certificate2?

查看:316
本文介绍了如何创建一个最小的虚拟X509Certificate2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好计算器用户,

我是单元测试.NET应用程序;一些单元测试涉及程序生成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:

主旨名称='(新System.Collections.Generic.Mscorlib_CollectionDebugView(result.Certificates))项目[0] .SubjectName'抛出一个异常类型'System.Security.Cryptography.CryptographicException

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?)

所以,问题:?什么是行代码最简单的(最少)的方式来编程生成一个X509Certificate2对象,这将不会抛出后场异常/属性访问?

非常感谢您的帮助!

推荐答案

我建议如下:


  1. 使用生成的证书的makecert

  2. 将证书添加到您的项目,改变它的生成操作嵌入的资源。

  3. 加载在你的单元测试设置资源的证书,请参阅下文。

代码:

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.

这篇关于如何创建一个最小的虚拟X509Certificate2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆