我有这段用PHP编写的代码,正如我所说的那样,它向HTTP请求添加了一些关于SSL证书的信息(它只是一个简单的http请求,不是&n;它?)。它已添加到正文请求或标题中,我不确定。
//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#制作这些东西。如果我知道它是如何在卷曲中完成的,就像它在它的封面下完全做的那样,这很容易。
我目前的要求。
//
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;
}
答案 0 :(得分:1)
要在HTTP请求中使用客户端证书(从.crt和.key文件加载),请在CreateHttpRequest
之前在return
方法中添加以下行:
string certificateText = File.ReadAllText("cert.crt");
string privateKeyText = File.ReadAllText("cert.key");
ICertificateProvider provider =
new CertificateFromFileProvider(certificateText, privateKeyText);
request.ClientCertificates.Add(provider.Certificate);
取自this answer。要CertificateFromFileProvider
安装OpenSSL.X509Certificate2.Provider Nuget包。
答案 1 :(得分:1)
使用OpenSSL library结束。
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版本,您可以使用我的fork。请记住,它还没有经过一直测试(不确定我是否会),所以有些东西可能无法正常工作。