如何使用C#语言传递密钥和证书

问题描述

嗨,我看到了演示代码,用于通过节点js使用证书身份验证API。

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();

            

但是我们的项目仅使用c#,所以我想知道如何在C#中发送带有密钥和证书证书的Web请求? 我尝试下面的代码,但似乎不正确

            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();
            }

它引发异常“ System.Security.Cryptography.CryptographicException:'找不到所请求的对象” 非常感谢

解决方法

X509Certificate类无法读取密钥。密钥也不应传输。

使用OpenSSL将密钥和pem合并到PKCS#12 / PFX文件中,然后尝试以下操作:

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

在将证书用于MutualTLS(客户端证书身份验证)时,可能会有一些requirements on the certificate,因此请确保该证书符合条件。