我需要向RESTAPI发出https请求。之前,我使用OpenSSL制作了证书申请和私钥。之后,我的证书申请已经由提供者签署,我拿了证书。因此我有证书和私钥。 问题:如何使用此证书,私钥和.net功能发出安全请求。 现在我提供代码,我已经借助我的直觉写了(注意:我使用BouncyCustle来读取pem文件):
static void Main(string[] args)
{
try
{
X509Certificate certificate = getCertificate("c:/xxx/certificate.pem");
AsymmetricKeyParameter privateKey = getPrivateKey("c:/xxx/key.pem");
HttpWebRequest webRequest = prepareWebRequest("https://xxxx",
"GET", certificate, privateKey);
WebResponse webResponse = webRequest.GetResponse();
}
catch(Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
Console.Write("Stack trace: {0}", e.StackTrace);
}
Console.ReadKey();
}
private static X509Certificate getCertificate(string pathToSertificate)
{
X509Certificate certificateBouncyCustle;
using (var fileStream = new FileStream(pathToSertificate, FileMode.Open))
using (var streamReader = new StreamReader(fileStream))
{
var pemReader = new PemReader(streamReader);
certificateBouncyCustle = (X509Certificate)pemReader.ReadObject();
}
return certificateBouncyCustle;
}
private static AsymmetricKeyParameter getPrivateKey(string pathToPrivateKey)
{
AsymmetricKeyParameter privateKey;
using (var fileStream = new FileStream(pathToPrivateKey, FileMode.Open))
using (var streamReader = new StreamReader(fileStream))
{
var pemReader = new PemReader(streamReader);
privateKey = ((AsymmetricCipherKeyPair)pemReader.ReadObject()).Private;
}
return privateKey;
}
private static HttpWebRequest prepareWebRequest(string url,
string method,
X509Certificate certificate,
AsymmetricKeyParameter privateKey)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method;
httpWebRequest.ClientCertificates.Add(DotNetUtilities.ToX509Certificate(certificate));
httpWebRequest.ContentType = "application/xml;charset=UTF8";
return httpWebRequest;
}