我很想知道是否有一种简单的方法来创建一个自签名证书,类似于下面的New-SelfSignedCertificate
命令(其他提供商也可以)。我希望只使用.NET库,而不需要P/Invoke或外部库(如Bouncy Castle),也不需要从应用程序调用PowerShell。
New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation $certificateStore -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certificateNotAfter
我想最简单的选择就是调用PowerShell或使用Nuget库,例如Bouncy Castle,如果没有外部设施就无法实现?虽然感觉如果我足够了解如何构建证书,就可以创建一个字节数组模板或类似的东西,并在X509Certificate2构造函数中使用它。
看起来需要执行以下操作:
public X509Certificate2 GenerateCertificate(string fileName, string password, string subjectName, StoreName storeName, DateTime endDate, DateTime notAfter, string provider = "Microsoft Enhanced RSA and AES Cryptographic Provider")
{
//Could provider be taken from https://dev59.com/yqDia4cB1Zd3GeqPMv94?
var newCertificate = new X509Certificate2(fileName, password, X509KeyStorageFlags.Exportable);
/*
# The following creates a self-signed certificate with one year of running time.
$currentDate = Get-Date
$certificateEndDate = $currentDate.AddYears(1)
$certificateNotAfter = $certificateEndDate.AddYears(1)
$certificateName = "https://www.test.com/test"
$certificateStore = "Cert:\LocalMachine\My"
New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation $certificateStore -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certificateNotAfter
*/
}
我发现了几个更多的选项:
Steve Syfuhs的博客文章在.NET中创建授权签名和自签名证书以及另一篇使用Mono扩展的SO帖子,Mono.Security无法设置多个KeyUsages。除了已经讨论过的选择外,它就是“类似于这样”。