您好计算器用户,
我是单元测试.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对象,这将不会抛出后场异常/属性访问?
非常感谢您的帮助!
推荐答案我建议如下:
代码:
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?
发布评论