Generating CSR in .NET Core


As I’m working on my first ever integration to ”Swish Handel” I needed to gernerate a CSR, preferably from .NET core. I found parts scattered over the web at best, so this is how I put them together.

A CSR is a Certificate Signing Request sent to a Certification Authority to generate a certificate. Certificates are used for encrypting traffic like SSL for https. PEM, Privacy Enhanced Mail, is a common format for sending CSRs and what was required in my case.

If you have no special needs, all you should probably do is change the subjectName string. This code generates a CSR based on a 4 096 bit key.

The Request class has one public method to call for returning a string containing the CSR in PEM-format.

The private method converts a DER encoded byte array into a PEM string.

[code language="csharp"]
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace CertificateService
{
   public class Request
   {
      public string GenerateCSR()
      {
         string subjectName =
            "CN=www.companyName.com,O=Company Name,OU=Department,T=Area,ST=State,C=Country";

         RSACryptoServiceProvider cryptoServiceProvider =
            new RSACryptoServiceProvider(4096);

         CertificateRequest certificateRequest =
            new CertificateRequest(subjectName,
               cryptoServiceProvider, HashAlgorithmName.SHA256,
               RSASignaturePadding.Pkcs1);

         return DERtoPEM(
               certificateRequest.CreateSigningRequest(
                  X509SignatureGenerator.CreateForRSA(
                     cryptoServiceProvider,
                     RSASignaturePadding.Pkcs1)));
      }

      private string DERtoPEM(byte[] bytesDER)
      {
         StringBuilder builder = new StringBuilder();
         builder.AppendLine("-----BEGIN CERTIFICATE REQUEST-----");

         string base64 = Convert.ToBase64String(bytesDER);

         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.AppendLine("-----END CERTIFICATE REQUEST-----");
         return builder.ToString();
      }
   }
}
[/code]

Lämna ett svar