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

Gus*_*uss 57 .net c# certificate self-signed

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

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

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

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

Gus*_*uss 71

此实现使用CX509CertificateRequestCertificateCOM对象(和朋友 - MSDN doc)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
    );
}
Run Code Online (Sandbox Code Playgroud)

可以X509Store使用X509Certificate2方法将结果添加到证书存储区或使用方法导出.

对于完全托管并且不依赖于Microsoft的平台,如果您对Mono的许可没有问题,那么您可以从Mono.Security查看X509CertificateBuilder.Mono.Security是Mono独立的,因为它不需要Mono的其余部分来运行,并且可以在任何兼容的.Net环境中使用(例如Microsoft的实现).

  • 如果你想使用我上面发布的代码示例,请将它与`certenroll.dll`结合使用,该文件应该在您的操作系统中可用(我认为是Windows 6.0及更高版本). (5认同)
  • 您也可以指出Mono有一个完全托管的makecert实现(由Mono.Security驱动,如您的描述),https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.如果有人想要探索Mono,这可以作为一个更好的例子. (3认同)
  • 我无法在Windows 8上工作:(在"enroll.CreateRequest"行上我得到一个System.UnauthorizedAccessException ... (3认同)
  • mono makecert.cs不安全.它只生成MD5和SHA1 ..不使用原样.在生成证书之前修改代码以使用SHA512. (3认同)
  • 请注意,大多数人认为SHA1是一个安全问题并且已弃用.特别是谷歌表示,他们将对仍在使用SHA1的网站进行排名,并在不久的将来完全排除.除非您具有无法以其他方式解决的特定向后兼容性问题,否则请勿使用SHA1. (2认同)

Dun*_*art 41

从.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-----");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 更新:.Export至关重要。导出到字节数组并重新导入到新的X509Certificate2之后,我便能够使用私钥。 (7认同)
  • 该证书似乎没有与之关联的私钥,有没有办法生成?我需要将证书导入到 IIS 的证书存储中。 (5认同)
  • 我实际上在 cert.PrivateKey.Get() 上得到了一个空引用异常,就好像 .CreateSelfSigned 没有生成它一样。有趣的是,.HasPrivateKey 属性返回 true。 (4认同)
  • @Viertaxa 你能发布你的代码来获取私钥吗? (3认同)
  • @Viertaxa 导出和重新导入对你来说是如何工作的?对我来说,它在访问私钥时抛出 systemnotsupported 异常。var req = new CertificateRequest("cn=test", ecdsa, System.Security.Cryptography.HashAlgorithmName.SHA256); X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); X509Certificate2 cert2 = 新 X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.PersistKeySet);} (2认同)
  • @DuncanSmart ecdsa 和 cert 对象实现“IDisposable”,并且应该在“using”语句中创建。 (2认同)
  • 很好的答案,对于任何使用生成的 pfx 在请求中使用 RSA 来签署 JWT 令牌的人来说都可以。`var request = new CertificateRequest($"CN={name}", RSA.Create(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);` (2认同)

dth*_*rpe 18

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

X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);
Run Code Online (Sandbox Code Playgroud)

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

  • 它是由Microsoft的CLR安全团队成员编写的.我认为目的是在某些时候将扩展折叠成Microsoft .NET版本,但我不认为这已经发生了.你可以通过codeplex网站ping shawnfa,看看它在哪里.当我在微软时,他是x509问题的首选.他对这个加密的东西非常好. (2认同)

dth*_*rpe 9

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

    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);
    }
Run Code Online (Sandbox Code Playgroud)

PluralSight.Crypto需要.NET 3.5或更高版本.

  • 我是选民,因为它是一个解决方案,但请注意使用PluralSight是一个问题有几个原因:(1)定义它是"免费"是有问题的 - 我可以在我的开源项目中使用它并在General下发布它的源代码公共许可证?我可以在我的商业产品中使用它并销售包含它的软件吗?对于那些不熟悉软件许可的人来说,这些问题的答案是****.(2)内部PluralSight使用P/Invoke,所以如果你在使用P/Invoke时遇到问题(其他的则不想自己编写),那么你仍然有问题. (5认同)
  • 我使用这个工具生成了证书,并且chrome抱怨签名使用SHA1,这被认为是不安全的. (2认同)

090*_*9EM 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);
}
Run Code Online (Sandbox Code Playgroud)