如何创建一个最小的虚拟X509Certificate2?

编程入门 行业动态 更新时间:2024-10-26 14:38:39
本文介绍了如何创建一个最小的虚拟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对象,这将不会抛出后场异常/属性访问?

非常感谢您的帮助!

推荐答案

我建议如下:

  • 使用生成的证书的makecert 。
  • 将证书添加到您的项目,改变它的生成操作嵌入的资源。
  • 加载在你的单元测试设置资源的证书,请参阅下文。
  • 代码:

    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?

    本文发布于:2023-11-05 08:45:16,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1560395.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:创建一个   最小

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!