Search code examples
c#opensslpemcrtder

How to convert .crt file to .pem file in c#


I have the crt file and I need to convert it to pem by code in C#, how can I do that?

command in openssl:

openssl x509 -inform der -in file.crt -out file.pem

Solution

  • On modern versions of .NET you can use the PemEncoding class:

    .NET 7:

    string pem = PemEncoding.WriteString("CERTIFICATE", der);
    

    .NET 5:

    string pem = new string(PemEncoding.Write("CERTIFICATE", der));
    

    But, in "stone-aged" .NET Framework you have to write the fairly easy transform yourself ($"-----BEGIN {label}-----\n{Convert.ToBase64String(der, Base64FormattingOptions.IncludeNewLines)}\n-----END {label}-----\n" being the short form).

    Borrowed/tweaked from the Remarks section of https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.certificaterequest.createsigningrequest?view=net-6.0#system-security-cryptography-x509certificates-certificaterequest-createsigningrequest:

    private static string PemEncode(string label, byte[] der)
    {
        StringBuilder builder = new StringBuilder();
    
        builder.Append("-----BEGIN ");
        builder.Append(label);
        builder.AppendLine("-----");
    
        string base64 = Convert.ToBase64String(pkcs10);
    
        int offset = 0;
        const int LineLength = 64;
    
        while (offset < base64.Length)
        {
            int lineEnd = Math.Min(offset + LineLength, base64.Length);
            builder.AppendLine(base64.Substring(offset, lineEnd - offset));
            offset = lineEnd;
         }
    
         builder.Append("-----END ");
         builder.Append(label);
         builder.AppendLine("-----");
         return builder.ToString();
    }