user788454
user788454

Reputation:

C# X509Certificate2.PrivateKey threw exception "invalid provider type specified."

I have a trusted CA issued SSL certificate installed on Windows Server 2019. When the following code in ASP.NET MVC controller was run, it did retrieve the X509Certificate2, its HasProviateKey property was true. But when its PrivateKey property was accessed, it threw a CryptographicException: "invalid provider type specified."

    X509Certificate2 certificate = null;
    X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    userCaStore.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
    X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindByThumbprint, "xyz...", true);

    if (findResult.Count != 1)
        throw new Exception("Certificate not found.");

    certificate = findResult[0];
    userCaStore.Close();

The reason I need to access the private key, was that the server needs to accept some long-lasting TCP socket connections, and I plan to use the SSL certificate's public/private key to do the typical handshake: the client generates a random AES key, and uses the public key to encrypt this AES key and sends it to the server. That is why I need to access the private key on the server side to decrypt the AES key.

How do I do it?

Upvotes: 0

Views: 1122

Answers (1)

user788454
user788454

Reputation:

I figured it out, partly. It has to do with the type of cryptography of the SSL certificate. I tried the same code to retrieve another trusted CA issued certificate and the PrivateKey property did present itself as RsaCryptoServiceProvider. The other thing that must be done is to right-click the certificate in the certificate store (mmc.exe) and select "All tasks | Manage private keys", and make sure the identity used by your code is there in a ACL.

Upvotes: 0

Related Questions