@bartojs 回答正确我必须使用CertificateRequest.Create。
我正在为我的 MITM 代理服务器应用程序创建自签名证书,因此这里是用于在 .Net Framework 4.7.2 中生成证书的工作代码,而无需像 Bouncy Castle 或 CERTENROLLIB 这样的外部 .dll 库
public static X509Certificate2 CreateMyCertificate(string host, bool isCA)
{
var validFrom = DateTimeOffset.UtcNow;
var validUntil = DateTimeOffset.UtcNow.AddYears(8);
X509Certificate2 certificate;
RSA rsaKey = Program.rootRSA;
if (isCA)
{
// create exportable Root private key
// will be used later as global variable Program.rootRSA
CspParameters cspParams = new CspParameters
{
KeyContainerName = Guid.NewGuid().ToString()
};
rsaKey = new RSACryptoServiceProvider(2048, cspParams);
}
// Request a certificate with the common name as the host using the key pair.
// Common Name (AKA CN) represents the server name protected by the SSL certificate.
var request = new CertificateRequest(
$"CN={host}",
rsaKey,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1
);
// Add Certificate Extensions
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection
{
new Oid("1.3.6.1.5.5.7.3.1")
}, true)
);
if (isCA)
{
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 1, false));
request.CertificateExtensions.Add(
new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
request.CertificateExtensions.Add(
new X509KeyUsageExtension(X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign, false));
certificate = request.CreateSelfSigned(validFrom, validUntil);
}
else
{
SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName(host.Replace("*.", ""));
request.CertificateExtensions.Add(sanBuilder.Build());
request.CertificateExtensions.Add(new X509Extension("2.5.29.35", Program.authorityKeyIdentifer, false));
request.CertificateExtensions.Add(new X509KeyUsageExtension(
X509KeyUsageFlags.KeyEncipherment, false));
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var unixTime = Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds);
var serial = BitConverter.GetBytes(unixTime);
certificate = request.Create(Program.rootCert, validFrom, validUntil.AddDays(-5), serial);
certificate.PrivateKey = Program.rootCert.PrivateKey;
}
var certificateBytes = certificate.Export(X509ContentType.Pfx, "");
// return certificate with persisted private key
return new X509Certificate2(certificateBytes, "", X509KeyStorageFlags.Exportable);
}
然后像这样使用它:
- 创建全局变量并将其命名为
rootCert 和rootRSA
- 在应用启动时检查计算机证书,如果 CA 未存储生成使用
rootCert = CreateMyCertificate("__MY_ROOT_CERTIFICATE", true);
- 将
rootCert 导出/存储到受信任的根位置
- 稍后如果有 https
connect 请求,我们可以使用生成证书
CreateMyCertificate("stackoverflow.com", false);
- 链接/创建
host 证书时,请确保已定义rootCert,因为它将在CreateMyCertificate() 方法中使用,如下行
if (isCA){...}
else
{
certificate = request.Create(Program.rootCert, validFrom, validUntil.AddDays(-5), serial);
}
注意为什么你不应该使用 CERTENROLLIB:
- 缓慢,因为它的操作需要直接从计算机证书中读取
- RSA 生成也比内置的 .net 4.7.2 慢
- 要获取私钥,我们首先需要安装证书,我们可以通过对计算机证书进行大量安装来导出到 PFX,它可以向您的计算机证书发送垃圾邮件。