Skip to main content
 首页 » 编程设计

c#之HttpWebRequest 客户端认证

2024年02月20日31zhengyun_ustc

我需要将一些 xml 发布到具有客户端证书身份验证的 https 站点,但未能成功。

我有 2 个由提供商提供的 .pem 文件,如下所示:(我无法发送所有如此剪切的数据)

证书.pem:

-----开始证书----- MIIC0DCCAjmgAwIBAgIKAd8CIHEBAwIEpjANBgkqhkiG9w0BAQUFADCBmTELMAkG

-----证书结束-----

key .pem:

-----开始RSA私钥----- MIICWwIBAAKBgQC+HN6jHJD1zoGLHYj1ycvg1yajll5zb3gExoWv7k+RbXLGuDEX

-----结束RSA私钥-----

我想做的是

private static string HttpRequest(string url, string data) 
        { 
            HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(url); 
 
 
            //string privateKey = File.ReadAllText("c:\\key.pem"); 
 
            //privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", ""); 
            //privateKey = privateKey.Replace("-----END RSA PRIVATE KEY-----", ""); 
            //privateKey = privateKey.Replace("\n", ""); 
 
            //Byte[] byteArr = Convert.FromBase64String(privateKey); 
 
            //How do I use below .pem files here to authentica 
            rq.ClientCertificates.Add(clientcert); 
            rq.Method = "POST"; 
            rq.Proxy = null; 
            rq.ContentType = "application/www-form-urlencoded"; 
 
            string dataToSend = data; 
 
            byte[] byteArray = Encoding.UTF8.GetBytes(dataToSend); 
            rq.ContentLength = byteArray.Length; 
 
            string responseFromServer = null; 
 
            try 
            { 
                Stream dataStream = rq.GetRequestStream(); 
                dataStream.Write(byteArray, 0, byteArray.Length); 
                dataStream.Close(); 
 
                WebResponse _WebResponse = rq.GetResponse(); 
                dataStream = _WebResponse.GetResponseStream(); 
 
                StreamReader reader = new StreamReader(dataStream); 
 
                responseFromServer = reader.ReadToEnd(); 
            } 
            catch (Exception ex) 
            { 
 
 
            } 
 
            return responseFromServer; 
        } 

请您参考如下方法:

您需要将您的私钥和pem证书转换成#pkcs12形式:

openssl pkcs12 -inkey private.key -in client_certificate.pem -export -out client_certificate.p12

在此之后,您可以在 C# 代码中指定此 p12 文件:

rq.ClientCertificates.Add(X509Certificate.CreateFromCertFile("c:\\client_certificate.p12"));