Jak utworzyć certyfikat z własnym podpisem przy użyciu C#?

Muszę utworzyć certyfikat z własnym podpisem (dla lokalnego szyfrowania - nie jest używany do zabezpieczania komunikacji), używając C#.

Widziałem kilka implementacji, które używają P/Invoke z Crypt32.dll , ale są one skomplikowane i trudno jest zaktualizować parametry - i chciałbym również uniknąć P / Invoke, jeśli w ogóle możliwe.

Nie potrzebuję czegoś, co jest międzyplatformowe - działanie tylko na Windows jest dla mnie wystarczające.

Najlepiej, aby wynik był Obiekt X509Certificate2, którego mogę użyć do wstawienia do magazynu certyfikatów systemu Windows lub wyeksportowania do pliku PFX.

Author: rstackhouse, 2012-12-10

5 answers

Ta implementacja używa obiektu CX509CertificateRequestCertificate COM (oraz friends - MSDN doc) z certenroll.dll do utworzenia żądania certyfikatu podpisanego samodzielnie i jego podpisania.

Poniższy przykład jest dość prosty (jeśli zignorujesz bity COM rzeczy, które dzieje się tutaj) i istnieje kilka części kodu, które są naprawdę opcjonalne (takie jak EKU), które są nie mniej przydatne i łatwe do dostosowania do użytku.

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

Wynik można dodać do magazynu certyfikatów za pomocą X509Store lub wyeksportować za pomocą metod X509Certificate2.

Dla w pełni zarządzanego i nie związanego z platformą Microsoftu, a jeśli nie masz nic przeciwko licencjonowaniu Mono, możesz spojrzeć na X509CertificateBuilderz Mono.Bezpieczeństwo . Mono.Bezpieczeństwo jest niezależne od Mono, ponieważ nie potrzebuje reszty Mono do uruchomienia i może być używane w każdym zgodnym środowisku. Net (np. implementacji Microsoftu).

 61
Author: Guss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-23 20:37:34

Inną opcją jest użycie CLR Security extensions library z CodePlex, która implementuje funkcję pomocniczą do generowania podpisanych certyfikatów x509:

X509Certificate2 cert = CngKey.CreateSelfSignedCertificate(subjectName);

Można również przyjrzeć się implementacji tej funkcji (w CngKeyExtensionMethods.cs) aby zobaczyć, jak jawnie utworzyć certyfikat z podpisem własnym w kodzie zarządzanym.

 17
Author: dthorpe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-12 17:58:47

Możesz użyć darmowego PluralSight.Biblioteka Crypto w celu uproszczenia programowego tworzenia podpisanych certyfikatów 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 wymaga. NET 3.5 lub nowszego.

 9
Author: dthorpe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-23 18:31:07

Od wersji. NET 4.7.2 można tworzyć własnoręcznie podpisane certy używając systemu .Ochrona.Kryptografia.X509certyfikaty.CertificateRequest .

Na przykład:

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-----");
    }
}
 1
Author: Duncan Smart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-27 10:44:29

To jest wersja Powershell dotycząca tworzenia certyfikatu. Możesz go użyć, wykonując polecenie. Sprawdź https://technet.microsoft.com/itpro/powershell/windows/pkiclient/new-selfsignedcertificate

Edit: zapomniałem powiedzieć, że po utworzeniu certyfikatu można użyć programu Windows "manage computer certificates", aby wyeksportować certyfikat do .CER lub innego typu.

 0
Author: Roger Deep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 15:25:42