C#中的PHP / Curl-SSL操作替代 [英] PHP/Curl-SSL operations alternative in C#
问题描述
我有这段用PHP编写的代码,据我推测,它向HTTP请求添加了有关SSL证书的一些信息(这只是一个简单的http请求,不是吗?)。我不确定它是否已添加到正文请求或标头中。
I have this piece of code written in PHP, which adds, as i presume, some information about an SSL-certificate to a HTTP-request(It's just a simple http-request, isn't it?). It's added either to body-request or header, that i don't know for sure.
//some code before that
curl_setopt($curl,CURLOPT_SSLCERT,'cert.crt');
curl_setopt($curl,CURLOPT_SSLKEY,'cert.key');
//some code after
//the request itself
$json_response = curl_exec($curl);
问题是-我不知道如何在C#中制作这些东西。如果我知道卷毛的完成方式(例如它在封面下的确切功能),那将很容易。
The problem is - i don't know how to make this stuff in C#. It'd be easy if i had any knowledge how it's done in curl, like what it exactly does under it's cover.
我当前的请求。
//
var request = CreateHttpRequest(url, method);
var json = param?.ToJson();
if (json != null)
{
var postData = Encoding.UTF8.GetBytes(json);
request.ContentLength = postData.Length;
using (var stream = request.GetRequestStream())
stream.Write(postData, 0, postData.Length);
}
using (var webResponse = request.GetResponse())
using (var streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
var result = streamReader.ReadToEnd();
return result.ParseJson(type);
}
//
private HttpWebRequest CreateHttpRequest(string url, HttpMethod method)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Accept = "application/json, application/javascript, text/*";
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.Method = method.ToString().ToUpper();
return request;
}
推荐答案
最终使用 OpenSSL库。
public X509Certificate2 CreateCertifacte(string pathToCertificate)
{
var keyBytes = File.ReadAllBytes($"{pathToCertificate}/cert.key");
var certBytes = File.ReadAllBytes($"{pathToCertificate}/cert.crt");
var certBio = new BIO(certBytes);
var keyBio = new BIO(keyBytes);
var key = CryptoKey.FromPrivateKey(keyBio, "_");
var cert = new X509Certificate(certBio);
var name = cert.SerialNumber+".pfx";
var stacks = new Stack<X509Certificate>();
new X509Store().AddTrusted(cert);
var certRealPkcs12 = new PKCS12("_", key, cert, stacks);
using (var file = BIO.File(name, "wb"))
{
file.SetClose(BIO.CloseOption.Close); // don't ask me why, i don't know. this one just works.
certRealPkcs12.Write(file);
}
certRealPkcs12.Dispose();
var realCertOut =
new X509Certificate2(File.ReadAllBytes(name), "_");
return realCertOut;
}
更新:
对于netstandard版本,您可以使用我的叉子。请记住,它尚未经过全面测试(不确定我是否会进行测试),因此可能无法正常工作。
For the netstandard version you can use my fork. Keep in mind that it hasn't been tested all the way through yet (not sure if i ever will), so something wont probably work.
这篇关于C#中的PHP / Curl-SSL操作替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!