0

I am send a CertificateRequest object to an REST API in base64string format by using below code and namespace System.Security.Cryptography.X509Certificates.

string certificateRequestBase64String = string.Empty;
// Generate a new RSA key pair.
using (RSA rsa = RSA.Create(keyLength))
{
    // Create a new X509CertificateRequest object.
    CertificateRequest certificateRequest = new CertificateRequest("x-subject", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

    // Add any additional extensions you want to include.
    certificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));

    // Convert the request to a PEM-encoded string.
    certificateRequestBase64String = Convert.ToBase64String(certificateRequest.CreateSigningRequest());
}

Then I am using below code to trying to convert back this base 64 string to CertificateRequest

X509Certificate2 x509Certificate2 = new X509Certificate2(Convert.FromBase64String(certificateRequestBase64String));

It throws Cannot find the requested object error.

Is there any other way to get this done?

Nithin B
  • 601
  • 1
  • 9
  • 26
  • 1
    Your problem is that you are trying to feed an `X509Certificate2` class with CSR. Certificate and CSR are very different objects. And `CertificateRequest` class is designed to generate requests, not parse/import. – Crypt32 Jan 30 '23 at 14:50
  • 1
    In addition to the answer, there's also a comment in the bottom that says we added this ability in .NET 7 ([LoadSigningRequestPem](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.certificaterequest.loadsigningrequestpem?view=net-7.0), and friends) – bartonjs Jan 31 '23 at 00:42
  • CertificateRequest description says `Represents an abstraction over the PKCS#10 CertificationRequestInfo and the X.509 TbsCertificate` - So, I assumed I can convert it to `X509Certificate`. But yes `CertificateRequest` would be the right thing to do. The problem is `CertificateRequest` doesn't have API accepting string or bytes atleast in .NET 6 which I am using. – Nithin B Jan 31 '23 at 02:03

0 Answers0