如何在.Net中创建一个全新的x509Certificate2?

发布于 2024-08-22 12:20:03 字数 164 浏览 5 评论 0原文

我从网上搜索,找到了很多从 .Net 中的文件生成新的 x509Certificate2 的示例,但是没有示例来展示如何从 .Net 中生成全新的 x509Certificate2 .net 的开始。

有谁可以告诉我如何在.net 中做到这一点吗?

I google it from web, find many examples to generate a new x509Certificate2 from a file in .Net, but there is no example to show how to generate a completely new x509Certificate2 from the beginning in .net.

Is there any one that can tell me how to do it in .net?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

十二 2024-08-29 12:20:03

查看CertificateRequest(名称空间:System.Security.Cryptography.X509Certificates)...

 public static X509Certificate2 GenerateSelfSignedCertificate()
    {
        string secp256r1Oid = "1.2.840.10045.3.1.7";  //oid for prime256v1(7)  other identifier: secp256r1
        
        string subjectName = "Self-Signed-Cert-Example";

        var ecdsa = ECDsa.Create(ECCurve.CreateFromValue(secp256r1Oid));

        var certRequest = new CertificateRequest($"CN={subjectName}", ecdsa, HashAlgorithmName.SHA256);

        //add extensions to the request (just as an example)
        //add keyUsage
        certRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));

        X509Certificate2 generatedCert = certRequest.CreateSelfSigned(DateTimeOffset.Now.AddDays(-1), DateTimeOffset.Now.AddYears(10)); // generate the cert and sign!

        X509Certificate2 pfxGeneratedCert = new X509Certificate2(generatedCert.Export(X509ContentType.Pfx)); //has to be turned into pfx or Windows at least throws a security credentials not found during sslStream.connectAsClient or HttpClient request...

     return pfxGeneratedCert;
}

Checkout CertificateRequest (Name Space: System.Security.Cryptography.X509Certificates)...

 public static X509Certificate2 GenerateSelfSignedCertificate()
    {
        string secp256r1Oid = "1.2.840.10045.3.1.7";  //oid for prime256v1(7)  other identifier: secp256r1
        
        string subjectName = "Self-Signed-Cert-Example";

        var ecdsa = ECDsa.Create(ECCurve.CreateFromValue(secp256r1Oid));

        var certRequest = new CertificateRequest(
quot;CN={subjectName}", ecdsa, HashAlgorithmName.SHA256);

        //add extensions to the request (just as an example)
        //add keyUsage
        certRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));

        X509Certificate2 generatedCert = certRequest.CreateSelfSigned(DateTimeOffset.Now.AddDays(-1), DateTimeOffset.Now.AddYears(10)); // generate the cert and sign!

        X509Certificate2 pfxGeneratedCert = new X509Certificate2(generatedCert.Export(X509ContentType.Pfx)); //has to be turned into pfx or Windows at least throws a security credentials not found during sslStream.connectAsClient or HttpClient request...

     return pfxGeneratedCert;
}
勿挽旧人 2024-08-29 12:20:03

您可以使用以下代码:

    static X509Certificate2 GenerateCertificate(string certName)
    {
        var keypairgen = new RsaKeyPairGenerator();
        keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

        var keypair = keypairgen.GenerateKeyPair();

        var gen = new X509V3CertificateGenerator();

        var CN = new X509Name("CN=" + certName);
        var SN = BigInteger.ProbablePrime(120, new Random());

        gen.SetSerialNumber(SN);
        gen.SetSubjectDN(CN);
        gen.SetIssuerDN(CN);
        gen.SetNotAfter(DateTime.MaxValue);
        gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
        gen.SetSignatureAlgorithm("MD5WithRSA");
        gen.SetPublicKey(keypair.Public);           

        var newCert = gen.Generate(keypair.Private);

        return new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
    }

要使其正常工作,请不要忘记添加对 BouncyCastle 库 的引用

Here's a code you can use:

    static X509Certificate2 GenerateCertificate(string certName)
    {
        var keypairgen = new RsaKeyPairGenerator();
        keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

        var keypair = keypairgen.GenerateKeyPair();

        var gen = new X509V3CertificateGenerator();

        var CN = new X509Name("CN=" + certName);
        var SN = BigInteger.ProbablePrime(120, new Random());

        gen.SetSerialNumber(SN);
        gen.SetSubjectDN(CN);
        gen.SetIssuerDN(CN);
        gen.SetNotAfter(DateTime.MaxValue);
        gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
        gen.SetSignatureAlgorithm("MD5WithRSA");
        gen.SetPublicKey(keypair.Public);           

        var newCert = gen.Generate(keypair.Private);

        return new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
    }

for this to work, don't forget to add reference to BouncyCastle library

玻璃人 2024-08-29 12:20:03

Open ssl 用于创建 x509 证书

1.从以下链接下载 Win64 Openssl。(Win64 OpenSSL v1.1.0j - 37mb 安装程序)
URL - https://slproweb.com/products/Win32OpenSSL.html

2.安装后设置系统路径环境变量。(path = C:\OpenSSL-Win64\bin)

3.打开命令提示符并将目录更改为桌面。

4.创建密钥命令:
私钥:openssl req -x509 -days 365 -newkey rsa:2048 -keyout cert-key.pem -out cert.pem
输入命令并按照说明进行操作。

5.现在桌面上有 2 个名为 cert-key.pem 和 cert.pem 的文件。要创建 .pfx 文件,请运行以下命令
openssl pkcs12 -export -in cert.pem -inkey cert-key.pem -out x509-cert.pfx
并按照说明进行操作(输入相同的密码)。

6.创建公钥命令:
openssl pkcs12 -in x509-cert.pfx -clcerts -nokeys -out x509-cert-public.pem
并按照说明进行操作。

7.将证书注册到mmc。

Open ssl for creating x509 certificate

1.Download the Win64 Openssl from the below link.(Win64 OpenSSL v1.1.0j - 37mb installer)
URL - https://slproweb.com/products/Win32OpenSSL.html

2.After installation set the system path environment variable.(path = C:\OpenSSL-Win64\bin)

3.Open command prompt and change the directory to desktop.

4.Command for key creation :
Private Key : openssl req -x509 -days 365 -newkey rsa:2048 -keyout cert-key.pem -out cert.pem
Enter the command and follow the instruction.

5.Now we have 2 files named cert-key.pem and cert.pem in desktop. To create the .pfx file run the below command
openssl pkcs12 -export -in cert.pem -inkey cert-key.pem -out x509-cert.pfx
and follow the instruction(enter the same password).

6.Command for public key creation :
openssl pkcs12 -in x509-cert.pfx -clcerts -nokeys -out x509-cert-public.pem
and follow the instruction.

7.Register the certificate to mmc.

旧情别恋 2024-08-29 12:20:03

您可以使用 PINVOKE 调用 Crypt32 来创建自签名证书。有一些

还有 Keith Brown 的 证书生成器,它是用托管代码编写的,具有 您可以使用的库

或者,您可以使用 Org.BouncyCastle.X509.X509V3CertificateGenerator 来使用 BouncyCastle,并使用 Org.BouncyCastle.Security.DotNetUtilities 中的实用程序方法并调用 ToX509Certificate( )

如果您想创建请求并由 CA 对其进行签名,这在 .NET 中实际上更容易,因为大多数这些类都可以作为 COM 互操作 DLL 导入。但这完全是另一个问题。

You can use PINVOKE to call into Crypt32 to create a self signed certificate. There is some sample code available which will generate one and put it in the certificate store for you.

There's also Keith Brown's certificate generator, which is written in managed code and has a library you can use.

Alternatively you can just use BouncyCastle using the Org.BouncyCastle.X509.X509V3CertificateGenerator and the use the utility methods in Org.BouncyCastle.Security.DotNetUtilities and call ToX509Certificate().

If you want to create a request and have it signed by a CA that's actually easier in .NET, as most of those classes can be imported as COM interop DLLs. But that's a whole other question.

桜花祭 2024-08-29 12:20:03

我认为你不能使用该 API 来做到这一点。但是您可以使用 Bouncy Castle (http://www.bouncycastle.org) 创建一个对象,然后将该对象转换为 X509Certificate2 对象(BC 有一些实用程序类可以执行此操作)。

-编辑-
看一下这些 BC 类:X509V3CertificateGenerator 和 X509Certificate

稍后将 BC X509Certificate 对象转换为常规 X509Certificate2 对象的 BC 实用程序类是:DotNetUtilities

I think you can't do it using that API. But you can create one using Bouncy Castle (http://www.bouncycastle.org) and later convert that object to a X509Certificate2 object (BC has some utility class for doing that).

-edit-
Take a look at these BC classes: X509V3CertificateGenerator and X509Certificate

The BC utility class that later will convert a BC X509Certificate object to a regular X509Certificate2 object is: DotNetUtilities

浮生面具三千个 2024-08-29 12:20:03
public X509Certificate2 GetCertificate()
{
    var config = InitConfiguration();
    var certificateSubject = "X509Subject";
    var certificateStoreName = "X509StoreName";
    var certificateStoreLocation = "X509StoreLocation";
    var thumbPrint = "ThumbPrint";

    var storeName = (StoreName)Enum.Parse(typeof(StoreName), certificateStoreName, true);
    var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), certificateStoreLocation, true);

    var certificateStore = new X509Store(storeName, storeLocation);
    certificateStore.Open(OpenFlags.ReadOnly);

    foreach (var storeCertificate in certificateStore.Certificates)
    {
        if (storeCertificate.Thumbprint.ToLower(System.Globalization.CultureInfo.CurrentCulture) == thumbPrint.ToLower(System.Globalization.CultureInfo.CurrentCulture))
        {return storeCertificate;
        }
    }
certificateStore.Close();
    return null;
}
public X509Certificate2 GetCertificate()
{
    var config = InitConfiguration();
    var certificateSubject = "X509Subject";
    var certificateStoreName = "X509StoreName";
    var certificateStoreLocation = "X509StoreLocation";
    var thumbPrint = "ThumbPrint";

    var storeName = (StoreName)Enum.Parse(typeof(StoreName), certificateStoreName, true);
    var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), certificateStoreLocation, true);

    var certificateStore = new X509Store(storeName, storeLocation);
    certificateStore.Open(OpenFlags.ReadOnly);

    foreach (var storeCertificate in certificateStore.Certificates)
    {
        if (storeCertificate.Thumbprint.ToLower(System.Globalization.CultureInfo.CurrentCulture) == thumbPrint.ToLower(System.Globalization.CultureInfo.CurrentCulture))
        {return storeCertificate;
        }
    }
certificateStore.Close();
    return null;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文