Как создать самозаверяющий сертификат с помощью C#?

Мне нужно создать самозаверяющий сертификат (для локального шифрования - он не используется для защиты связи), используя C#.

Я видел несколько реализаций, которые используют P/Invoke с Crypt32.dll, но они сложны и сложно обновлять параметры - и я также хотел бы избежать P/Invoke, если это вообще возможно.

Мне не нужно что-то кроссплатформенное - мне достаточно работать только на Windows.

В идеале результатом должен быть объект X509Certificate2, который я могу использовать для вставки в хранилище сертификатов Windows или экспорта в файл PFX.

8 ответов

Решение

Эта реализация использует CX509CertificateRequestCertificate COM-объект (и друзья - 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
    );
}

Результат может быть добавлен в хранилище сертификатов с помощью X509Store или экспортируется с использованием X509Certificate2 методы.

Если вы полностью управляемы и не привязаны к платформе Microsoft, и если вы согласны с лицензией Mono, вы можете взглянуть на X509CertificateBuilder от Mono.Security. Mono.Security является независимым от Mono тем, что для запуска не требуется остальная часть Mono, и его можно использовать в любой совместимой среде.Net (например, в реализации Microsoft).

Начиная с.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));

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

Другой вариант - использовать библиотеку расширений безопасности CLR от CodePlex, которая реализует вспомогательную функцию для создания самозаверяющих сертификатов x509:

X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);

Вы также можете посмотреть на реализацию этой функции (в CngKeyExtensionMethods.cs) чтобы увидеть, как явно создать самоподписанный сертификат в управляемом коде.

Если это поможет кому-то еще, мне нужно было сгенерировать тестовый сертификат в формате 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);
        }

Вы можете использовать бесплатную библиотеку 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);
    }

PluralSight.Crypto требует.NET 3.5 или новее.

Вот консольное приложение, которое запрашивает имя хоста пользователя, срок действия в днях и пароль.

      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();

Расширение ответа 0909EMs с помощью SubjectAlternativeNames на основе кода, найденного здесь: Понимание самозаверяющих сертификатов в 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посмотрите здесь /questions/33815337/generatsiya-i-podpis-zaprosa-sertifikata-s-ispolzovaniem-chistogonet-framework/33815347#33815347

Это версия Powershell о том, как создать сертификат. Вы можете использовать его, выполнив команду. Проверьте https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

Изменить: забыл сказать, что после создания сертификата вы можете использовать программу Windows "Управление сертификатами компьютера", чтобы экспортировать сертификат в.CER или другой тип.

Другие вопросы по тегам