84

我需要使用 C# 创建一个自签名证书(用于本地加密 - 它不用于保护通信)。

我见过一些使用P/InvokeCrypt32.dll的实现,但它们很复杂,而且很难更新参数——而且我也想尽可能避免使用 P/Invoke。

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

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

4

7 回答 7

94

从 .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-----");
    }
}
于 2018-09-27T10:44:29.477 回答
81

此实现使用CX509CertificateRequestCertificateCOM 对象(和朋友 - MSDN doccertenroll.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 的实现)。

于 2012-12-10T17:46:24.083 回答
20

另一种选择是使用 CodePlex 的CLR 安全扩展库,它实现了一个辅助函数来生成自签名 X.509 证书:

X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);

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

于 2012-12-12T00:31:57.743 回答
11

您可以使用免费的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 或更高版本。

于 2012-12-10T23:04:06.617 回答
6

如果它对其他人有帮助,我需要使用Duncan Smart 的答案生成 PEM 格式的测试证书(因此需要 crt 和密钥文件) ,我制作了以下内容......

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);
}
于 2020-08-24T13:02:17.360 回答
0

根据此处找到的代码使用SubjectAlternativeNames扩展0909EM 答案Understanding self-signed certificate in 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

于 2021-05-21T13:48:23.557 回答
-2

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

编辑:忘了说创建证书后,您可以使用 Windows“管理计算机证书”程序,将证书导出为 .CER 或其他类型。

于 2017-05-27T15:17:05.513 回答