title: How to create a X509Certificate2 from crt and key files?
body: <p>I am trying to create a X509Certificate2 with the private key. To get the private key I am traying this code:</p>
  
  <pre><code>using System;
  using System.Security.Cryptography;
  
  namespace whats_new
  {
      public static class RSATest
      {
          public static void Run(string keyFile)
          {
              using var rsa = RSA.Create();
  
              byte[] keyBytes = System.IO.File.ReadAllBytes(keyFile);
              rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);
  
              Console.WriteLine($"Read {bytesRead} bytes, {keyBytes.Length - bytesRead} extra byte(s) in file.");
              RSAParameters rsaParameters = rsa.ExportParameters(true);
              Console.WriteLine(BitConverter.ToString(rsaParameters.D));
          }
      }
  }
  </code></pre>
  
  <p>I get this code from Microsoft docs: <a href="https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#cryptographic-key-importexport" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#cryptographic-key-importexport</a></p>
  
  <p>But I get the error "ASN1 corrupted data" in this line:</p>
  
  <pre><code>rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);
  </code></pre>
  
  <p>Really what I would like to do it is to create a X509Certificate2 certificate with the crt and key, because in my gRPC service I need that the certificate has both. It is because I have created the certificate with OpenSsl I generated one file for the certificate and another file for the key.</p>
  
  <p>Thanks.</p>