如何向REST发出安全请求,使用公钥签名证书,以及使用证书请求生成的私钥

时间:2016-07-28 10:53:55

标签: c# rest https request

我需要向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;
}

0 个答案:

没有答案