如何使用C#创build自签名证书?

我需要使用C#创build自签名证书(用于本地encryption – 不用于保护通信)。

我已经看到一些使用Crypt32.dll的 P / Invoke实现,但是它们很复杂,很难更新这些参数,而且我还想尽可能地避免P / Invoke。

我不需要跨平台的东西 – 只在Windows上运行对我来说已经足够了。

理想情况下,结果将是一个X509Certificate2对象,我可以使用它插入Windows证书存储或导出到PFX文件。

此实现使用CX509CertificateRequestCertificate COM对象(和朋友certenroll.dll 文档 )创build一个自签名证书请求并签名。

下面的例子是非常简单的(如果你忽略了这里的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方法导出。

对于一个完全pipe理,而不是绑定到微软的平台,如果你可以用Mono的授权,那么你可以看看Mono.Security的 X509CertificateBuilder 。 Mono.Security是Mono独立的,因为它不需要Mono的其余部分运行,并且可以在任何兼容的.Net环境(例如Microsoft的实现)中使用。

另一种select是使用来自CodePlex的CLR安全扩展库 ,该库实现了一个辅助函数来生成自签名的x509证书:

 X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName); 

您还可以查看该函数的实现(在CngKeyExtensionMethods.cs ),以了解如何在托pipe代码中显式创build自签名证书。

您可以使用免费的PluralSight.Crypto库来简化对自签名x509证书的编程创build:

  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或更高版本。

这是关于如何创build证书的Powershell版本。 您可以通过执行该命令来使用它。 检查https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

编辑:忘了说创build证书后,可以使用Windows的“pipe理计算机证书”程序,将证书导出为.CER或其他types。