Home > Back-end >  Generate x509 certificate on c# not returning expected result
Generate x509 certificate on c# not returning expected result

Time:03-30

I am using .net 6.0 with .net core and I'd like to create x509 certificate and use this with k8s c# client.

For creating x509 certificate I have method like this:

public static byte[] GenerateCertificate(string name)
{
    var sanBuilder = new SubjectAlternativeNameBuilder();
    sanBuilder.AddIpAddress(IPAddress.Loopback);
    sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
    sanBuilder.AddDnsName("localhost");
    sanBuilder.AddDnsName(Environment.MachineName);

    var distinguishedName = new X500DistinguishedName(name);

    using var rsa = RSA.Create(4096);
    var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256,RSASignaturePadding.Pkcs1);

    request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature , false));
    request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new ("1.3.6.1.5.5.7.3.1") }, false));
    request.CertificateExtensions.Add(sanBuilder.Build());
    request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
    var csr = request.CreateSigningRequest();
    return csr;
}

And I am expecting result like this for generating certificate on k8s:

-----BEGIN CERTIFICATE REQUEST-----
    certificate code long code
-----END CERTIFICATE REQUEST-----

How to manage to get result like this?

CodePudding user response:

You are looking for the PEM format, but the function provides DER.

From the docs:

"To convert the return value to PEM format, make a string consisting of -----BEGIN CERTIFICATE REQUEST-----, a newline, the Base-64-encoded representation of the request (by convention, linewrapped at 64 characters), a newline, and -----END CERTIFICATE REQUEST-----."

So what you need is

return
    "-----BEGIN CERTIFICATE REQUEST-----\r\n"  
    Convert.ToBase64String(csr)  
    "\r\n-----END CERTIFICATE REQUEST-----";

You also need to change your function to return string. If you want to return it as byte you need to decide an encoding. For example, you could do return Encoding.UTF8.GetBytes(base64Request);

  • Related