0

嗨,我看到了使用节点 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# 中发送带有密钥和 Cert 证书的 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:'找不到请求的对象”非常感谢

4

1 回答 1

0

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

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

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

将证书用于 MutualTLS(客户端证书身份验证)时,可能对证书有一些要求,因此请确保证书符合条件。

于 2020-11-05T14:13:45.583 回答