【发布时间】:2021-03-09 17:22:23
【问题描述】:
我有许多域证书的 PEM 文件。我已经了解了如何从文件中读取单个 PEM 对象,并且可以将证书与私钥区分开来。现在我需要知道我找到的每个证书的主题名称。不幸的是,似乎不存在任何文档,而且我无法在网络上找到其他谈论这样做的用户。我发现的大多数代码都是关于 Java 的,并且使用了当前库中不可用的名称(至少对于 C#)。无论从证书中读取 CN 值是否是一项奇特的任务,我都需要这样做。
这是我目前发现的:
安装 NuGet 包 Portable.BouncyCastle 1.8.8
using (var streamReader = new StreamReader("cert.pem"))
{
var pemReader = new PemReader(streamReader);
while (true)
{
object pemObject = pemReader.ReadObject();
if (pemObject == null)
break;
switch (pemObject)
{
case RsaPrivateCrtKeyParameters privateKey:
Console.WriteLine("Private key");
break;
case X509Certificate certificate:
Console.WriteLine("Certificate");
// This has ALL entries from the subject, including CN
Console.WriteLine(" Subject: " + certificate.SubjectDN);
// This is a convoluted list of lists of lists of stuff that seems to contain
// the CN values somewhere deep within but I can't figure out how to access it
var derSequence = certificate.SubjectDN.ToAsn1Object() as DerSequence;
// And I'm not sure if these are the correct types to use and what other
// types to be prepared for in real life.
// Like the below untyped list of untyped lists of stuff seems to be working
// to extract the alternative names (SAN) from a certificate:
var altNames = certificate.GetSubjectAlternativeNames()?
.OfType<System.Collections.ArrayList>()
.SelectMany(l => l.OfType<string>())
.ToList();
if (altNames != null)
{
foreach (string str in altNames)
{
Console.WriteLine(" Subject alternative name: " + str);
}
}
break;
}
}
}
如果 BouncyCastle 是错误的工具,我应该使用 .NET 集成类(.NET Core 3.1 或 5.0),请告诉我并解释一下。我还需要其他数据,例如证书的颁发时间或过期时间。
这是我现在使用的解决方法。对于像 X509 这样复杂的东西,这可能是一种非常笨拙的方法。但这就是我从中理解的水平。
var match = Regex.Match(certificate.SubjectDN.ToString(), @"(?:^|,)CN=([^,]+)");
if (match.Success)
{
Console.WriteLine(" Subject: " + match.Groups[1].Value);
}
【问题讨论】:
-
我认为它就在那里。 Bouncycastle 在
x509目录中拥有处理证书的类,例如x509.X509Certificate。该类有一个属性SubjectDN,可以检查 CN 和 Subject 名称的其他组成部分。
标签: c# bouncycastle x509