首页 > 解决方案 > X509Certificate 中的公钥和私钥

问题描述

我正在使用 C# System.Security.Cryptography 库为 apache 创建证书。我已经有一个 CA 证书,我尝试使用它来签署服务器证书。

我正在使用 CertificateRequest.Create 方法来创建证书。不幸的是,它没有提供我需要的 apache 私钥(.pem/.crt 和 .key)。如何保存证书并获取 apache 所需的两个文件?

OpenSSL 不是我的解决方案。

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

我可以通过这样做来保存签名证书的公钥:

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

如何获取私钥并将其保存为 .key 文件?

标签: c#apachex509certificate

解决方案


With .NET Core 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).


推荐阅读