简体   繁体   English

X509Certificate 中的公钥和私钥

[英]Public and private key in X509Certificate

I am using the C# System.Security.Cryptography library to create a certificate for apache.我正在使用 C# System.Security.Cryptography 库为 apache 创建证书。 I already have a CA certificate which I try to use for signing the server certificate.我已经有一个 CA 证书,我尝试使用它来签署服务器证书。

I am using the CertificateRequest.Create method to create the certificate.我正在使用 CertificateRequest.Create 方法来创建证书。 Unfortunately it doesn't provide a private key which I need for apache (.pem/.crt and.key).不幸的是,它没有提供我需要的 apache(.pem/.crt 和 .key)的私钥。 How do I save the certificate and get both needed files for apache?如何保存证书并获取 apache 所需的两个文件?

OpenSSL is not a solution for me. OpenSSL 不是我的解决方案。

X509Certificate2 signedCert = request.Create(issuerCert, DateTimeOffset.Now, 
    DateTimeOffset.Now.AddYears(5), new byte[] { 1, 2, 3, 4 });

I can save the public key of the signed cert by doing this:我可以通过这样做来保存签名证书的公钥:

File.WriteAllText(path + "cert.pem",
            "-----BEGIN CERTIFICATE-----\r\n"
            + Convert.ToBase64String(signedCert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
            + "\r\n-----END CERTIFICATE-----");

How do I get the private key and save it as.key file?如何获取私钥并将其保存为 .key 文件?

With .NET Core 3.0:使用 .NET 核心 3.0:

File.WriteAllText(path + "cert.pem",
    "-----BEGIN PRIVATE KEY-----\r\n"
        + Convert.ToBase64String(
            key.ExportPkcs8PrivateKey(),
            Base64FormattingOptions.InsertLineBreaks)
        + "\r\n-----END PRIVATE KEY-----");

Where key is any AsymmetricAlgorithm type (which you need to just... have somewhere -- probably passed into the CertificateRequest constructor, but since you created a chain-signed certificate the CertificateRequest would have worked from a public-key-only instance).其中key是任何 AsymmetricAlgorithm 类型(您需要...有某个地方 - 可能传递到 CertificateRequest 构造函数中,但由于您创建了链签名证书,因此 CertificateRequest 可以从仅公钥实例中工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM