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

101

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

我看到了一些使用P/InvokeCrypt32.dll的实现,但它们很复杂,更新参数很难-如果可能的话,我也想避免P/Invoke。

我不需要跨平台的东西-只在Windows上运行就足够了。

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


1
为了未来的读者,我已经在以下网址发布了我的BouncyCastle代码:https://granadacoder.wordpress.com/2016/11/04/service-bus-and-custom-self-signed-certificates-with-a-high-availabilitymultiple-computing-nodes-in-the-farm/。这将创建两个证书。一个是“受信任的根”证书,第二个是由(第一个)受信任的根证书“签名”的证书。 - granadaCoder
现在可以不使用COM或外部依赖项来实现此操作,请参见https://dev59.com/XlYM5IYBdhLWcg3w7jc1。 - bartonjs
1
在VS2019中:项目属性->签名->ClickOnce->创建测试证书? - Andrew
4
问题是如何以编程方式创建自签名证书。有很多创建一次性自签名证书的方法,例如使用 CertUtil 或 openssl,但问题的背景是构建软件,在用户计算机上自动生成这些证书。 - Guss
8个回答

116

自 .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-----");
    }
}

6
这个证书似乎没有关联的私钥,有办法生成一个吗?我需要将该证书导入到IIS的证书库中。 - Viertaxa
5
实际上,我在cert.PrivateKey.Get()处遇到了空引用异常,就好像.CreateSelfSigned没有生成它一样。有趣的是,.HasPrivateKey属性返回为true。 - Viertaxa
12
更新:看起来 .Export 是至关重要的。将证书导出为字节数组并重新导入到一个新的 X509Certificate2 中,我就能够使用私钥了。 - Viertaxa
3
@Viertaxa,导出和重新导入对你有用吗?对我来说,在访问私钥时会抛出“SystemNotSupported”异常。{var ecdsa = System.Security.Cryptography.ECDsa.Create(); var req = new CertificateRequest("cn=test", ecdsa, System.Security.Cryptography.HashAlgorithmName.SHA256); X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); X509Certificate2 cert2 = new X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.PersistKeySet);} - Vivek Baranwal
3
@Viertaxa,你能否请发布获取私钥的代码? - Daniel
显示剩余7条评论

82

这个实现使用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的实现)中使用。


3
你可以指出Mono有一个完全托管的makecert实现(由Mono.Security提供支持),https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs 如果有人想探索Mono,这将是更好的示例。 - Lex Li
6
如果你想使用我上面发布的代码示例,需要与 certenroll.dll 一起使用,该文件应该已经包含在您的操作系统中(我认为 Windows 6.0 及以上版本都有)。 - Guss
5
我无法在Windows 8上使其工作 :( 在"enroll.CreateRequest"这一行中,我收到了一个System.UnauthorizedAccessException ... - Mirek
2
请注意,大多数人认为SHA1存在安全问题并已被弃用。特别是谷歌表示,他们将降低仍在使用SHA1的网站的排名,并在不久的将来完全排除。除非您有无法通过其他方式解决的特定向后兼容性问题,请勿使用SHA1。 - Guss
3
"mono makecert.cs" 不安全,它只生成具有 MD5 和 SHA1 的证书...不要直接使用。在生成证书之前,修改代码以使用 SHA512。 - Max
显示剩余25条评论

21

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

X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);

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


CLR安全工作看起来很有趣 - 你知道这个项目和微软公司之间的关系吗?该项目页面似乎声称它是由编写标准Security.Cryptography类的同一团队编写的,但我除了一些博客之外没有看到任何参考。作为一个安全软件包,重要的是要知道它是否受到与官方.NET发布相同的安全审查。我的直觉也没有得到帮助,因为最后一个版本是针对.NET 3.5的,但提供的功能仍然缺失于.NET 4.x... - Guss
2
这是由微软CLR安全团队的成员编写的。我认为意图是将这些扩展功能合并到某个Microsoft .NET版本中,但我不认为这已经发生了。您可以通过codeplex网站联系shawnfa,了解其进展情况。当我在微软时,他是我寻求x509问题答案的人选。他在这方面的加密知识非常出色。 - dthorpe
这个使用的是哪个SHA? - rollsch
如何访问私钥?当我尝试访问时,会出现异常。 - Mitch3091

13

如果有人需要帮助,我需要生成一个PEM格式的测试证书(因此需要crt和key文件),使用来自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);
}

谢谢!在我的情况下,我需要一个RSA证书,并且这个很好用!我正在使用这段代码的变体来创建内存中的证书,以便在一些单元测试中运行。 - Cameron Tinker
这个解决方案已经解决了私钥属性为Null的问题。 - undefined

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


9
我投赞成票是因为这是一个解决方案,但请注意,使用 PluralSight 存在几个问题:(1) 定义它为“免费”的是有问题的——我能在我的开源项目中使用它并在通用公共许可证下发布其源代码吗?我能在我的商业产品中使用它并销售包含它的软件吗?对于不熟悉软件许可的人来说,这些问题的答案是否定的。(2) 内部 PluralSight 使用 P/Invoke,因此如果您使用 P/Invoke 存在问题(除了不想自己编写它之外),则仍然存在问题。 - Guss
3
我使用这个工具生成了证书,但Chrome提示该证书签名所使用的SHA1算法被认为不安全。 - Giedrius
@Guss 源代码中的每个文件都有一个顶部注释:// This code was written by Keith Brown, and may be freely used. - Andrzej Gis
@gisek - 我指的是PluralSight上提供该库下载的页面(不像答案链接中作为示例项目的一部分),而且那里的许可证有问题(我不记得细节了)。现在我找不到那个页面(6年后),也找不到任何官方网站提供该库,所以此时我只能评论说“可以自由使用”是一种可怕的许可证,因为它与“公共领域”无法正常工作的原因大致相同(请参见这篇文章以获取更多详细信息:https://creativecommons.org/share-your-work/public-domain/cc0/),但对于大多数人来说可能足够好了。 - Guss

1

这是一个控制台应用程序,它会询问用户主机名、过期天数和密码。

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

Console.Write("Enter hostname: ");
string hostname = Console.ReadLine();

Console.Write("Enter days until expiration: ");
int days = int.Parse(Console.ReadLine());

Console.Write("Enter password, enter to skip: ");
string password = Console.ReadLine();

// Generate a new RSA key pair
RSA rsa = RSA.Create();

// Create a certificate request with the specified subject and key pair
CertificateRequest request = new CertificateRequest(
    $"CN={hostname}",
    rsa,
    HashAlgorithmName.SHA256,
    RSASignaturePadding.Pkcs1);

// Create a self-signed certificate from the certificate request
X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(days));

// Export the certificate to a file with password
byte[] certBytes = string.IsNullOrEmpty(password) 
    ? certificate.Export(X509ContentType.Pfx) 
    : certificate.Export(X509ContentType.Pfx, password);
File.WriteAllBytes($"{hostname}.pfx", certBytes);

Console.WriteLine($"Certificate for {hostname} created successfully and will expire on {certificate.NotAfter}.");
Console.WriteLine($"Path: {Path.Combine(AppContext.BaseDirectory, hostname)}.pfx");
Console.ReadKey();

1

基于在此处找到的代码,通过添加SubjectAlternativeNames来扩展0909EMs answer了解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://dev59.com/XlYM5IYBdhLWcg3w7jc1#48210587


-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接