I use .cer and .key files in custom web server for validate ssl with SslStream.AuthenticateAsServerAsync(). creating process of X509Certificate2 is some things like this:

var bytes = File.ReadAllBytes(certificatePath);
using var publicKey = new X509Certificate2(bytes,default(string));


var privateKeyText = File.ReadAllText(privateKeyPath);
var privateKeyBlocks = privateKeyText.Split("-", StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim('\n')).ToArray();
var privateKeyBytes = Convert.FromBase64String(privateKeyBlocks[1]);

        
using var rsa = RSA.Create();

if (privateKeyBlocks[0] == "BEGIN PRIVATE KEY")
   {
      rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
   }
else if (privateKeyBlocks[0] == "BEGIN RSA PRIVATE KEY")
   {
      rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
   }

var keyPair = publicKey.CopyWithPrivateKey(rsa);
return new X509Certificate2(keyPair.Export(X509ContentType.Pfx));

In useing .pfx every this is ok, but by use this code for replace .pfx file (and generating process of it) with .cer and .key files, in SslStream.AuthenticateAsServerAsync() i got this error:

System.Security.Authentication.AuthenticationException: The server mode SSL must use a certificate with the associated private key.

Other way that i use for do this :

 X509Certificate2 certWithKey = default;
 try
 {
   string keyPem = File.ReadAllText(keyFile);
   byte[] keyDer = UnPem(keyPem);
   using (X509Certificate2 certOnly = new X509Certificate2(cerFile))
   {
       using (RSA rsa = RSA.Create())
       {
           // For "BEGIN PRIVATE KEY"
           rsa.ImportPkcs8PrivateKey(keyDer, out _);
           var tmp = certOnly.CopyWithPrivateKey(rsa);
           certWithKey = new X509Certificate2(tmp.Export(X509ContentType.Pfx));
       }
   }
   Serilog.Log.ForContext("Path", cerFile).Information("Create certificate from {FileName} successfully.", Path.GetFileName(cerFile));
 }
 catch (Exception ex)
 {
    Logger.LogError(ex, "Error in create certificate from {Path}", cerFile);
 }
 return certWithKey;
 static byte[] UnPem(string pem)
 {
    // This is a shortcut that assumes valid PEM
    // -----BEGIN words-----\nbase64\n-----END words-----
    const string Dashes = "-----";
    int index0 = pem.IndexOf(Dashes);
    int index1 = pem.IndexOf('\n', index0 + Dashes.Length);
    int index2 = pem.IndexOf(Dashes, index1 + 1);
    return Convert.FromBase64String(pem.Substring(index1, index2 - index1));
}

Also in .net 5 use this new way:

return X509Certificate2.CreateFromPemFile(certificatePath,privateKeyPath);

But Problem not solved.

All things that i want is create X509Certificate2 from .cer and .key files,not from .pfx file. I don't know that and where is problem.create X509Certificate2 cause problem or i miss some thins else(for example in validate sslstream). tanks for help me to know problem and best way for doing this.

1

There are 1 answers

0
Ali Qamsari On

By tanks of bartonjs, my problem solved with this:

string pass = Guid.NewGuid().ToString();
var certificate = X509Certificate2.CreateFromPemFile(certificatePath, privateKeyPath);
return new X509Certificate2(certificate.Export(X509ContentType.Pfx, pass), pass);

Create in-memory .pfx type certificate from .cer file with random password and use it instead of original certificate.