使用安全证书使用.NET的cURL请求

时间:2012-11-23 17:11:09

标签: c# curl webrequest

我有一个需要安全证书的cURL命令。我试图用C#中的WebRequest替换调用。

这是curl命令:

curl -d“uid = UUUUUU& password = PPPPPP& active = Y& type = I”https://www.aidap.naimes.faa.gov/aidap/XmlNotamServlet - key aidap_key.pem --cacert aidap_ca.pem --cert aidap_client.pem:start123 -k -O

我遇到的问题是如何合并--key, - cacert和--cert参数。目前我正在设置WebRequest.PreAuthenticate = true并使用我的证书库中的安全证书的名称和密码创建NetworkCredential(我假设在--key, - cartrt等中)。

当我运行下面的代码时,我收到了403禁止异常。

有什么想法吗?

这是我正在使用的代码:

 public void RetrieveNotams()
        {
            string myURL = "https://www.aidap.naimes.faa.gov/aidap/XmlNotamServlet";

            HttpWebRequest req;

            NetworkCredential myCred = new NetworkCredential("AAAAA", "BBBBB");

            req = (HttpWebRequest)WebRequest.Create(myURL);

            req.PreAuthenticate = true;

            req.Credentials = myCred;

            req.Method = "POST";

            req.ContentType = "application/x-www-form-urlencoded";
            string postData = "uid=UUUUUU&password=PPPPPP&active=Y&type=I";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = byteArray.Length;

            using (Stream dataStream = req.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
            }

            req.GetResponse();

        }

1 个答案:

答案 0 :(得分:1)

我在

的帮助下弄明白了

http://www.codeproject.com/Articles/28395/Attaching-a-digital-certificate-public-key-to-an-H

我从证书存储中获取证书,并将其添加到请求的证书集合中。并取出了PreAuthenticate代码。

这是更新后的代码:

public void RetrieveNotams()
{
    string myURL = "https://www.example.com/SecureSite";

    // Open the certificate store for the current user in readonly mode,
    // and find the certificate I need to user
    X509Store xstore = new X509Store(StoreLocation.CurrentUser);

    xstore.Open(OpenFlags.ReadOnly);

    X509Certificate cert=null; 

    foreach (X509Certificate c in xstore.Certificates)
        if(c.Subject.StartsWith("CN=aidapuser"))
            cert=c;          

    HttpWebRequest req;

    req = (HttpWebRequest)WebRequest.Create(myURL);

    // add the certificate to the request
    req.ClientCertificates.Add(cert);

    req.Method = "POST";

    req.ContentType = "application/x-www-form-urlencoded";
    string postData = "uid=UUUUUUU&password=PPPPPP&active=Y&type=I";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    req.ContentLength = byteArray.Length;

    // add the parameters to POST to the URL
    using (Stream dataStream = req.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
    }

    // grab the response and show the first 10 lines

    using (StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream()))
    {

        for (int i = 0; i < 10; i++)
            Console.WriteLine(sr.ReadLine());
    }

}