Ask Your Question
4

How can I generate PEM certificates using .NET Framework 4.8?

asked 2023-04-30 01:42:31 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-04-30 02:08:02 +0000

nofretete gravatar image

You can use the .NET Framework 4.8's System.Security.Cryptography namespace to generate PEM certificates.

Here's an example code snippet that generates a self-signed certificate and exports it in PEM format:

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        // Generate a new RSA key pair
        RSACryptoServiceProvider keyPair = new RSACryptoServiceProvider(2048);

        // Create a self-signed X.509 certificate
        X509Certificate2 certificate = new X509Certificate2(
            keyPair.Export(X509ContentType.Cert),
            null,
            X509KeyStorageFlags.Exportable);

        // Export the private key in PEM format
        string privateKeyPem = ExportPrivateKey(keyPair);

        // Export the certificate in PEM format
        string certificatePem = ExportCertificate(certificate);

        Console.WriteLine("Private key (PEM):\n" + privateKeyPem);
        Console.WriteLine("Certificate (PEM):\n" + certificatePem);
    }

    public static string ExportPrivateKey(RSA privateKey)
    {
        byte[] privateKeyBlob = privateKey.ExportRSAPrivateKey();
        StringBuilder builder = new StringBuilder();
        builder.AppendLine("-----BEGIN PRIVATE KEY-----");
        builder.AppendLine(Convert.ToBase64String(privateKeyBlob, Base64FormattingOptions.InsertLineBreaks));
        builder.AppendLine("-----END PRIVATE KEY-----");
        return builder.ToString();
    }

    public static string ExportCertificate(X509Certificate2 certificate)
    {
        StringBuilder builder = new StringBuilder();
        builder.AppendLine("-----BEGIN CERTIFICATE-----");
        builder.AppendLine(Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
        builder.AppendLine("-----END CERTIFICATE-----");
        return builder.ToString();
    }
}

Note that this example exports the private key in unencrypted PEM format, which is not secure. If you need to export the private key in encrypted PEM format, you should use a more secure implementation of the ExportPrivateKey() method.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-30 01:42:31 +0000

Seen: 10 times

Last updated: Apr 30 '23