0

Hi I Saw the demo code for consume the Certificate Authentication API with node js.

var https = require('https'),                  // Module for https
    fs =    require('fs');                     // Required to read certs and keys

    var options = {
       hostname: 'xxx',         
       path: '/courses/tags?sortBy=0',      
       method: 'GET',                   // Method : Get or POST
       key: fs.readFileSync('C://testNodeJs/key.pem'),      //Input the directory for key.pem
       cert: fs.readFileSync('C://testNodeJs/cert.pem')         //Input the directory for cert.pem
       //passphrase: 'InputPassWord'                        //Input the passphrase, please remember to put ',' End of Line for cert         
    };

    makeAPICall = function(response) {
       var str = '';    
       response.on('data', function (chunk) {
          str += chunk;
       });

       response.on('end', function () {
          console.log(str);
       });
    }

https.request(options, makeAPICall).end();

            

But our project just use c#, so I want to know how do I send Web Request with key and Cert certificate in C#? I try to below code, but seems not correct

            var url1 = @"xxx";
            HttpWebRequest request1 = WebRequest.Create(url1) as HttpWebRequest;
            request1.Method = "GET";
            request1.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate("key.pem"));
            request1.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate("cert.pem"));
            
            // Get response
            using (HttpWebResponse response = request1.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output
                var result = reader.ReadToEnd();
            }

It throw a exception "System.Security.Cryptography.CryptographicException: 'Cannot find the requested object" thanks a lot

Lucky
  • 1
  • 1

1 Answers1

0

The X509Certificate class cannot read a key. A key should also NOT be transmitted.

Use OpenSSL to merge the key and the pem into a PKCS#12/PFX file and try this instead:

request1.ClientCertificates.Add(
  new X509Certificate2(
    "certAndKey.pfx", 
    password));

When using a certificate for MutualTLS (Client Certificate authentication) there might be some requirements on the certificate, so ensure the certificate is eligible.

Daniel Fisher lennybacon
  • 3,865
  • 1
  • 30
  • 38