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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2315257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:57:41  来源:igfitidea点击:

how to create a completely new x509Certificate2 in .net?

.netx509certificate2

提问by travellover

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

我从网上谷歌它,找到许多示例从 .net 中的文件生成一个新的 x509Certificate2,但没有一个示例显示如何从 .net 开始生成一个全新的 x509Certificate2。

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

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

Thank you very much.

非常感谢。

回答by Arsen Zahray

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

为此,不要忘记添加对BouncyCastle 库的引用

回答by blowdart

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

您可以使用 PINVOKE 调用 Crypt32 以创建自签名证书。有一些可用的示例代码可以生成一个并将其放入证书存储区。

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

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

Alternatively you can just use BouncyCastle using the Org.BouncyCastle.X509.X509V3CertificateGeneratorand the use the utility methods in Org.BouncyCastle.Security.DotNetUtilitiesand call ToX509Certificate().

或者,您可以使用 BouncyCastleOrg.BouncyCastle.X509.X509V3CertificateGenerator和使用实用程序方法 inOrg.BouncyCastle.Security.DotNetUtilities和 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.

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

回答by user3532037

Open ssl for creating x509 certificate

打开 ssl 以创建 x509 证书

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

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

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

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

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

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

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

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

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 key.pem out -x509-cert.pfxand follow the instruction(enter the same password).

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

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

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

7.Register the certificate to mmc.

7.将证书注册到mmc。

回答by ?ubrówka

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).

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

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

-edit- 看看这些 BC 类:X509V3CertificateGenerator 和 X509Certificate

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

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

回答by user3532037

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