使用C#传递证书和密钥文件

时间:2018-03-15 14:33:38

标签: c# ssl

我们有新的流程需要使用证书文件和私钥文件进行Web身份验证。

文件:

-----BEGIN CERTIFICATE-----  
MIIFtjj.......k=  
-----END CERTIFICATE-----  

-----BEGIN RSA PRIVATE KEY-----  
MIIEow.......jsTC9bx  
-----END RSA PRIVATE KEY-----

python和curl的示例可以正常工作:

curl -s -k --key ./my.key --cert ./my.cert https://[domain]/[endpoint]/[id_number]/

requests.get(url, cert=(CERT_FILE, KEY_FILE), verify=False)

适用于Linux环境,我们还负责一些Windows应用程序,我们需要访问该服务。

使用“openssl”创建证书文件 openssl x509 -inform pem -in certificate.pem> my.cert openssl rsa -in key.pem> my.key

将证书安装到Windows计算机不是一种选择,因为我们可能没有这种级别的访问权限。

我试过了:

ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.ServerCertificateValidationCallback = ( a, b, c, d ) => true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.DefaultConnectionLimit = 9999;

var certificate = new X509Certificate2( CERT_FILE );
byte[] buffer = Helpers.DecodeOpenSslPrivateKey( keyfile );  // reads in the rsa file minus the start end tags and converts from base64
certificate.PrivateKey = Helpers.DecodeRsaPrivateKey( buffer );
// similiar to: https://github.com/StefH/OpenSSL-X509Certificate2-Provider/blob/master/src/OpenSSL.PrivateKeyDecoder/OpenSSLPrivateKeyDecoder.cs

HttpWebRequest request = WebRequest.Create( url ) as HttpWebRequest;
request.PreAuthenticate = true;
request.AllowAutoRedirect = true;
request.ClientCertificates.Add( certificate );

WebResponse response = await request.GetResponseAsync();
// fails here with: The request was aborted: Could not create SSL/TLS secure channel

有很多地方人们建议将密钥转换为pkcs12或其他一些openssl导出,但是这些密钥在使用CURL或python的同一台机器上工作。 CURL显示通过TLS12的连接,我正在运行.Net 4.51(升级到4.6不是一个选项)

0 个答案:

没有答案