1

I have a program that find a certificate into a store, and test if the rsa private key is present.

var store = (StoreName.CertificateAuthority, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, "a02274af4e74defc0bf2ffb45e2d90bdbb1282f9", false);

if (certs.Count > 0)
{
    Console.WriteLine("Cert found");
    X509Certificate2 cert = certs[0];
    var rsa = cert.GetRSAPrivateKey();
    if (rsa == null)
        Console.WriteLine("rsa failed");
    else
        Console.WriteLine("rsa ok");
}

On Windows everything is fine with the certificate in pfx installed into the store.

On linux, the certificate is found, but the private key is not. I used this SO answer to convert my pfx to crt file : https://stackoverflow.com/a/16724275/1083225 and I put the crt file into /usr/local/share/ca-certificates, and executed update-ca-certificates If I look into the crt file, the rsa is present.

It's a .NETCoreApp 1.1

Community
  • 1
  • 1
Bastiflew
  • 1,136
  • 3
  • 18
  • 31

1 Answers1

4

The cert loader for LM\Root on Linux only loads the files as X.509 DER or X.509 PEM, so no private key material is loaded.

If you want a self-issued certificate to be root trusted, adding it to wherever your distro considers to be the root trust for OpenSSL is correct. If you also need to access the private key associated with that certificate, you'll need to have it also be in a CurrentUser store, or for you to manually load it as a PFX.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • This does even not work with direct loading pfx. or with CurrentUser. Looks like PrivateKey will remain always blank on linux, It does show "HasPrivateKey": true on the X509Certificate2 object, but then "PrivateKey.Key" remains blank/empty. at least for certs with RSA algorithm keys. – Subodh Wasankar Mar 11 '22 at 17:26
  • @SubodhWasankar The X509Certificate2.PrivateKey and X509Certificate2.PublicKey.Key properties are deprecated. You should instead use X509Certificate2.GetRSAPrivateKey()/GetRSAPublicKey()/Get{Alg}{Public|Private}Key(). – bartonjs Mar 11 '22 at 17:27
  • Is there any documentation? Actually, I am trying to create X509SigningCredentials from this cert, and it is creating invalid X509SigningCredentials because X509Certificate2 is not as expected with Private keys. In Linux containers. works on windows. – Subodh Wasankar Mar 11 '22 at 17:31
  • 1
    @SubodhWasankar https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.privatekey?view=net-6.0 The big red box at the top :). – bartonjs Mar 11 '22 at 17:34