开发者

How do I include an X509Certificate in a HttpWebRequest?

开发者 https://www.devze.com 2023-02-22 12:44 出处:网络
I am testing an aspx page I wish to use to post to but I cannot seem to send the certificate over with the data. Here is my client code:

I am testing an aspx page I wish to use to post to but I cannot seem to send the certificate over with the data. Here is my client code:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string postData = "age=23&state=47";
byte[] data = encoding.GetBytes(postData);
X509Certificate x509certificate = X509Certificate.CreateFromCertFile(@"C:\Documents and Settings\rcimbalo\My Documents\Downloads\SSL Certificates\testCert.cer");
string key = x509certificate.GetPublicKeyString();
string certData = Encoding.ASCII.GetString(x509certificate.Export(X509ContentType.Cert));
string pks12 = Encoding.ASCII.GetString(x509certificate.Export(X509ContentType.Pkcs12));
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3493/Index.aspx");
myRequest.Credentials = new NetworkCredential("xxxx", "yyyy");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
myRequest.ClientCertificates.Add(x509certificate);
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
System.IO.StreamReader st = new StreamReader(((HttpWebResponse)myRequest.GetRespon开发者_如何学Gose()).GetResponseStream());
Console.Write(st.ReadLine());

and here is the code from my aspx page:

protected void Page_Load(object sender, EventArgs e)
{
if (this.CheckCredentials())
{
    string data = this.Context.Request.Form.ToString();
}
}

private bool CheckCredentials()
{
    string userName = User.Identity.Name;
    HttpClientCertificate certificate = Request.ClientCertificate;
    if (certificate.IsPresent)
    {
        string w = certificate.Get("SUBJECT 0");
        return true;
    }
    return false;
}

There is never a certificate present.

I found this earlier post X509Certificate not getting transmitted to the server

But did not understand the answer. I created a certificate using the MakeCert.exe utility but I do not really understand why it does not work.


A client certificate is sent over a SSL connection (https://....). This is not possible with the built in asp.net development server, but is possible if you use the new IIS Express or a local IIS instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消