Search code examples
c#.netrsax509certificate2cng

How can I test a CNG key for exchangeable?


I have taken a certificate:

X509Certificate2 x509 = store.Certificates.Find(X509FindType.FindBySubjectName, "CNGTestCert", false)[0];

and now I want to get the providertype parameter. But I cant do x509.PrivateKey. In result of this I used var key = x509.GetRSAPrivateKey();. How can I get out of this key the ProviderType to decide the KeyNumber (looks like here: referencesource.microsoft.com). Or is there a easier way to test the private key for key function (key was created for signature or exchange)?


Solution

  • I found a way to check CNG certificate for exchangeable. If I read the private key of certificate by var privateKey = (cngCert.GetRSAPrivateKey() as RSACng).Key;, did I get the KeyUsage. The "KeyAgreement" flag marks the certificate for usage of secret agreement generation and key exchange.

    var privateKey = (cngCert.GetRSAPrivateKey() as RSACng).Key;
            
            if(privateKey.KeyUsage.HasFlag(CngKeyUsages.KeyAgreement))
            {
                //is for KeyExchange 
            }