.NET 中的 X509Certificate2 和 X509Certificate 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1182612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:04:35  来源:igfitidea点击:

What is the difference between X509Certificate2 and X509Certificate in .NET?

.netsslcertificatex509certificate

提问by Kyle

What is the difference between the two?

两者有什么区别?

回答by p.campbell

The x509Certificatewas introduced in .NET v1.0/1.1 and was (comparatively) limited in its functionality. It can be used to get information about an existing certificate (valid dates, issuer, etc.). It had simple methods/operations (i.e. reading a cert from disk).

X509证书(相对的)限制在其功能是在.NET 1.0引入/ 1.1和是。它可用于获取有关现有证书的信息(有效日期、颁发者等)。它有简单的方法/操作(即从磁盘读取证书)。

The x509Certificate2is a subclass of x509Certificate with additional functionality.

x509Certificate2是具有附加功能的x509Certificate的子类。

  • It represents an actual X509 certificate.
  • It was new in the .NET Framework v2.0.
  • This class gives you access to all the V2 and V3 properties (authority key identifier and key usage).
  • It supports loading a certificate from a certificate store.
  • 它代表一个实际的 X509 证书。
  • 它是 .NET Framework v2.0 中的新增功能。
  • 此类使您可以访问所有 V2 和 V3 属性(权限密钥标识符和密钥用法)。
  • 它支持从证书库加载证书。

回答by So Many Goblins

For completeness' sake, here is a copy of the relevant section of the site linked toin @dommer's answer, since the site may no longer be up and only in Google's cache for who-knows-how long:

为完整起见,这里是@dimmer 回答中链接到网站相关部分的副本,因为该网站可能不再启动,并且只在 Google 的缓存中存在不知道多长时间:

Version 1.1 of the framework had very little other than the X509Certificate class to allow you to manipulate certificates. In fact, the v1.1 X509Certificate class gave only basic support: it only gave access to the X509 version 1 fields (like the valid from and valid to dates, subject and public key) but not version 2 fields (like the authority key identifier) nor version 3 fields (like the key usage). There was no support to load a certificate from a certificate store, nor does it have the facilities to access certificate revocation lists or certificate trust lists. Microsoft improved on this with the Web Services Enhancement (WSE) toolkit extending the certificate class and providing classes to access certificate stores. These classes can now be found in the .NET 3.0/2.0 framework library.

The first big change is a new class called X509Certificate2 which derives from X509Certificate. The methods to access the X509 certificate fields have been deprecated and now the class has properties to access those fields. In addition, if the certificate has an associated private key then the class gives access to this key. There are methods that allow you to provide a password if the private key is protected by one. The password is passed through a SecureString parameter which is a special type that makes sure that when the object is no longer being used the memory it occupied will be written over so that the password cannot be read by another process on the machine. Secure strings and other forms of protected data will be covered in a later section.

Since X509Certificate2 derives from X509Certificate it means that you can call the static methods CreateFromeCertFile and CreateFromSignedFile through the X509Certificate2 class. However, these methods return an X509Certificate object and you cannot down cast this to a X509Certificate2 object. The X509Certificate class has been improved in version 3.0/2.0: it provides properties to access some of the X509 fields; it provides Import and Export methods to initialize an object from a byte array or generate a byte array from the certificate and it has constructors that will create an object from a file (ASN.1 DER) and from a byte array. Interestingly, the X509Certificate2 class has a constructor that can create an X509Certificate2 object from an X509Certificate object. Note that although an X509Certificate object can only show the X509v1 fields it can be created from an X509v3 certificate and so if you create an X509Certificate2 object from an X509Certificate object you will be able to access the X509v3 fields.

除了 X509Certificate 类之外,该框架的 1.1 版几乎没有什么可以让您操作证书。事实上,v1.1 X509Certificate 类只提供基本支持:它只提供对 X509 版本 1 字段(如有效起始日期和有效日期、主题和公钥)的访问权限,而不是版本 2 字段(如授权密钥标识符) ) 也不是版本 3 字段(如密钥用法)。不支持从证书存储加载证书,也没有访问证书吊销列表或证书信任列表的工具。Microsoft 通过 Web 服务增强 (WSE) 工具包扩展了证书类并提供了访问证书存储的类,从而对此进行了改进。现在可以在 .NET 3.0/2.0 框架库中找到这些类。

第一个重大变化是一个名为 X509Certificate2 的新类,它派生自 X509Certificate。访问 X509 证书字段的方法已被弃用,现在该类具有访问这些字段的属性。此外,如果证书具有关联的私钥,则该类可以访问此密钥。如果私钥受密码保护,则有一些方法允许您提供密码。密码通过 SecureString 参数传递,该参数是一种特殊类型,可确保当不再使用对象时,它占用的内存将被覆盖,以便机器上的其他进程无法读取密码。后面的部分将介绍安全字符串和其他形式的受保护数据。

由于 X509Certificate2 派生自 X509Certificate,这意味着您可以通过 X509Certificate2 类调用静态方法 CreateFromeCertFile 和 CreateFromSignedFile。但是,这些方法返回一个 X509Certificate 对象,您不能将其强制转换为 X509Certificate2 对象。X509Certificate 类在 3.0/2.0 版本中得到了改进:它提供了访问一些 X509 字段的属性;它提供 Import 和 Export 方法来从字节数组初始化对象或从证书生成字节数组,并且它具有将从文件 (ASN.1 DER) 和字节数组创建对象的构造函数。有趣的是,X509Certificate2 类有一个构造函数,可以从 X509Certificate 对象创建 X509Certificate2 对象。

回答by ftexperts

To convert an X.509 cert from "X509Certificate" to "X509Certificate2", try something like this:

要将 X.509 证书从“X509Certificate”转换为“X509Certificate2”,请尝试以下操作:

X509Certificate  X509  = sslStream.RemoteCertificate;
X509Certificate2 X5092 = new X509Certificate2(X509);

回答by Walter Vehoeven

For those that would like to read the certificate and use this to authenticate one would simply create a X509Certificate2 and pass the X509Certificate in it's constructor.

对于那些想要读取证书并使用它进行身份验证的人,只需创建一个 X509Certificate2 并在其构造函数中传递 X509Certificate。

For a signed assembly (the exe) the code would be code like this, and I omit error validation for simplicity.

对于签名程序集(exe),代码将是这样的代码,为了简单起见,我省略了错误验证。

Module m = Assembly.GetEntryAssembly().GetModules()[0];
using (var cert = m.GetSignerCertificate())
using (var cert2 = new X509Certificate2(cert))
{
   var _clientHandler = new HttpClientHandler();
   _clientHandler.ClientCertificates.Add(cert2);
   _clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
   var myModel = new Dictionary<string, string>
   {
       { "property1","value" },
       { "property2","value" },
   };
   using (var content = new FormUrlEncodedContent(myModel))
   using (var _client = new HttpClient(_clientHandler))
   using (HttpResponseMessage response = _client.PostAsync($"{url}/{controler}/{action}", content).Result)
   {
       response.EnsureSuccessStatusCode();
       string jsonString = response.Content.ReadAsStringAsync().Result;
       var json = new Newtonsoft.Json.JsonSerializer();
       var myClass = JsonConvert.DeserializeObject<MyClass>(json);
    }
}

Obviously you're class isn't called MyClass but some business object that you'd expect from the web service.

显然,您的班级不称为 MyClass,而是您期望从 Web 服务获得的一些业务对象。

You can send a class to your action by sending the property & value you require filled. You can now ensure that the request you received is from a valid mobile or windows client by reading the request certificate like so:

您可以通过发送您需要填写的属性和值来向您的操作发送一个类。您现在可以通过读取请求证书来确保您收到的请求来自有效的移动或 Windows 客户端,如下所示:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {           
       X509Certificate2 clientCertInRequest = Request.HttpContext.Connection.ClientCertificate;
       if (!clientCertInRequest.Verify() || !AllowedCerialNumbers(clientCertInRequest.SerialNumber))
       {
            Response.StatusCode = 404;
            return null;
       }
       //your code
   }

}

}

What is left is to set your webserver to accept client certificates... You can read all about properties that come from the new format and you have secured your public web service, something most fail to do as just being authorized isn't good enough anymore (if it ever was)

剩下的就是将您的网络服务器设置为接受客户端证书......您可以阅读来自新格式的所有属性,并且您已经保护了您的公共网络服务,因为仅获得授权还不够好,所以最无法做到的事情不再(如果曾经是)