[英]How can I create a self-signed certificate using C#?
我需要使用 C# 創建一個自簽名證書(用於本地加密 - 它不用於保護通信)。
我已經看到一些使用P/Invoke和Crypt32.dll 的實現,但它們很復雜並且很難更新參數 - 如果可能的話,我也想避免 P/Invoke 。
我不需要跨平台的東西——只在 Windows 上運行對我來說已經足夠了。
理想情況下,結果將是一個 X509Certificate2 對象,我可以使用它插入到 Windows 證書存儲或導出到PFX文件。
從 .NET 4.7.2 開始,您可以使用System.Security.Cryptography.X509Certificates.CertificateRequest創建自簽名證書。
例如:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
public class CertificateUtil
{
static void MakeCert()
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
// Create PFX (PKCS #12) with private key
File.WriteAllBytes("c:\\temp\\mycert.pfx", cert.Export(X509ContentType.Pfx, "P@55w0rd"));
// Create Base 64 encoded CER (public key only)
File.WriteAllText("c:\\temp\\mycert.cer",
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
}
}
此實現使用CX509CertificateRequestCertificate
COM對象(和朋友- MSDN文檔)從certenroll.dll
創建一個自簽名的證書請求和簽署。
下面的示例非常簡單(如果您忽略這里發生的 COM 內容),並且代碼中有一些部分是真正可選的(例如 EKU),它們仍然有用且易於使用適應您的使用。
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
{
// create DN for subject and issuer
var dn = new CX500DistinguishedName();
dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
// create a new private key for the certificate
CX509PrivateKey privateKey = new CX509PrivateKey();
privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
privateKey.MachineContext = true;
privateKey.Length = 2048;
privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
privateKey.Create();
// Use the stronger SHA512 hashing algorithm
var hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
AlgorithmFlags.AlgorithmFlagsNone, "SHA512");
// add extended key usage if you want - look at MSDN for a list of possible OIDs
var oid = new CObjectId();
oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
var oidlist = new CObjectIds();
oidlist.Add(oid);
var eku = new CX509ExtensionEnhancedKeyUsage();
eku.InitializeEncode(oidlist);
// Create the self signing request
var cert = new CX509CertificateRequestCertificate();
cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.Subject = dn;
cert.Issuer = dn; // the issuer and the subject are the same
cert.NotBefore = DateTime.Now;
// this cert expires immediately. Change to whatever makes sense for you
cert.NotAfter = DateTime.Now;
cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
cert.Encode(); // encode the certificate
// Do the final enrollment process
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(cert); // load the certificate
enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
string csr = enroll.CreateRequest(); // Output the request in base64
// and install it back as the response
enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
PFXExportOptions.PFXExportChainWithRoot);
// instantiate the target class with the PKCS#12 data (and the empty password)
return new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), "",
// mark the private key as exportable (this is usually what you want to do)
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
);
}
結果可以使用X509Store
添加到證書存儲或使用X509Certificate2
方法導出。
對於完全托管且不綁定到 Microsoft 的平台,並且如果您對 Mono 的許可沒有意見,那么您可以查看Mono.Security中的X509CertificateBuilder 。 Mono.Security 獨立於 Mono,因為它不需要 Mono 的其余部分來運行,並且可以在任何兼容的 .Net 環境中使用(例如 Microsoft 的實現)。
另一種選擇是使用 CodePlex 的CLR 安全擴展庫,它實現了一個輔助函數來生成自簽名 X.509 證書:
X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);
您還可以查看該函數的實現(在CngKeyExtensionMethods.cs
)以了解如何在托管代碼中顯式創建自簽名證書。
您可以使用免費的PluralSight.Crypto 庫來簡化自簽名 X.509 證書的編程創建:
using (CryptContext ctx = new CryptContext())
{
ctx.Open();
X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
new SelfSignedCertProperties
{
IsPrivateKeyExportable = true,
KeyBitLength = 4096,
Name = new X500DistinguishedName("cn=localhost"),
ValidFrom = DateTime.Today.AddDays(-1),
ValidTo = DateTime.Today.AddYears(1),
});
X509Certificate2UI.DisplayCertificate(cert);
}
PluralSight.Crypto 需要 .NET 3.5 或更高版本。
如果它對其他人有幫助,我需要生成 PEM 格式的測試證書(因此需要 crt 和密鑰文件),使用Duncan Smart的答案,我生成了以下內容...
public static void MakeCert(string certFilename, string keyFilename)
{
const string CRT_HEADER = "-----BEGIN CERTIFICATE-----\n";
const string CRT_FOOTER = "\n-----END CERTIFICATE-----";
const string KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----\n";
const string KEY_FOOTER = "\n-----END RSA PRIVATE KEY-----";
using var rsa = RSA.Create();
var certRequest = new CertificateRequest("cn=test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// We're just going to create a temporary certificate, that won't be valid for long
var certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(1));
// export the private key
var privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey(), Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(keyFilename, KEY_HEADER + privateKey + KEY_FOOTER);
// Export the certificate
var exportData = certificate.Export(X509ContentType.Cert);
var crt = Convert.ToBase64String(exportData, Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(certFilename, CRT_HEADER + crt + CRT_FOOTER);
}
根據此處找到的代碼使用SubjectAlternativeNames擴展0909EMs 答案: 了解 c# 中的自簽名證書
public static void MakeCert(string certFilename, string keyFilename)
{
const string CRT_HEADER = "-----BEGIN CERTIFICATE-----\n";
const string CRT_FOOTER = "\n-----END CERTIFICATE-----";
const string KEY_HEADER = "-----BEGIN RSA PRIVATE KEY-----\n";
const string KEY_FOOTER = "\n-----END RSA PRIVATE KEY-----";
using var rsa = RSA.Create();
var certRequest = new CertificateRequest("cn=test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// Adding SubjectAlternativeNames (SAN)
var subjectAlternativeNames = new SubjectAlternativeNameBuilder();
subjectAlternativeNames .AddDnsName("test");
certRequest.CertificateExtensions.Add(subjectAlternativeNames.Build());
// We're just going to create a temporary certificate, that won't be valid for long
var certificate = certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddDays(1));
// export the private key
var privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey(), Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(keyFilename, KEY_HEADER + privateKey + KEY_FOOTER);
// Export the certificate
var exportData = certificate.Export(X509ContentType.Cert);
var crt = Convert.ToBase64String(exportData, Base64FormattingOptions.InsertLineBreaks);
File.WriteAllText(certFilename, CRT_HEADER + crt + CRT_FOOTER);
}
對於使用X509KeyUsageExtension
的密鑰用法的定義,請看這里https://stackoverflow.com/a/48210587/226278
這是關於如何創建證書的 Powershell 版本。 您可以通過執行命令來使用它。 檢查https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate
編輯:忘了說,創建證書后,您可以使用Windows“管理計算機證書”程序,將證書導出為.CER或其他類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.