如何在HttpWebRequest中包含x509证书?

本文关键字:x509 证书 包含 HttpWebRequest | 更新日期: 2023-09-27 17:48:58

我正在测试一个aspx页面,我希望使用它来发布,但我似乎无法将证书与数据一起发送。下面是我的客户端代码:

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.GetResponse()).GetResponseStream());
Console.Write(st.ReadLine());
下面是我的aspx页面的代码:
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;
}

从来没有证书存在。

我发现了这个早先的帖子x509证书没有传输到服务器

但不明白答案。我使用MakeCert.exe实用程序创建了一个证书,但我真的不明白为什么它不起作用。

如何在HttpWebRequest中包含x509证书?

客户端证书通过SSL连接(https://....)发送。对于内建的asp.net开发服务器,这是不可能的,但如果使用新的IIS Express或本地IIS实例,这是可能的。