Use Microsoft CNG library to load key from KSP and use it to initiate two-way-ssl mutual authentication

DV 6 Reputation points
2020-11-17T16:57:49.983+00:00

I have to connect to a backend service that is secured using two way ssl. The certificate I use for this handshake resides in an HSM. I've installed the HSM providers KSP software.
I'm using Microsoft's CNG library to lookup certificate generated in an HSM using the code below(C#) .

            CngKeyCreationParameters cng = new CngKeyCreationParameters
            {
                KeyUsage = CngKeyUsages.AllUsages,
                Provider = new CngProvider("My Crypto Key Storage Provider"),
                KeyCreationOptions = CngKeyCreationOptions.MachineKey
            };

            CngKey cngKey = CngKey.Open("My Key Container");
            RSACng rsaKey = new RSACng(cngKey);

How do I use this CngKey/RSACng object to start the mutual authentication request?

var request = (HttpWebRequest)WebRequest.Create("https://host/mutual-auth-endpoint");
//request.ClientCertificates.Add(...); .//This requires a X509Certificate2 object

The above two lines of code require an X509Certificate2 object. How do I go from CngKey/RSACng object to an X509Certificate2 object.
Or is there a totally different approach using the CNG library ?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,571 Reputation points
    2020-11-18T05:40:15.737+00:00

    If you want to get an X509Certificate2 with RSACng, try this:

        CngKeyCreationParameters cng = new CngKeyCreationParameters  
        {  
            KeyUsage = CngKeyUsages.AllUsages,  
            Provider = new CngProvider("My Crypto Key Storage Provider"),  
            KeyCreationOptions = CngKeyCreationOptions.MachineKey  
        };  
        CngKey cngKey = CngKey.Open("My Key Container");  
        RSACng rsaKey = new RSACng(cngKey);  
      
        X509Certificate2 cert = new X509Certificate2();  
        var certWithKey = cert.CopyWithPrivateKey(rsaKey);  
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.