本节内容:
C#实现https双向认证
操作方法,如下:
1,把浏览器中的证书导出为cer文件。
2,https 双向认证
例子:
复制代码 代码示例:
using System;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Net.Security;
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// string url = "https://192.168.6.120/";
ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
//Uri uri = new Uri("https://www.jb200.com/");
Uri uri = new Uri("https://192.168.6.120/");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
X509Certificate cer = new X509Certificate("F:csharp2.cer");
request.ClientCertificates.Add(cer);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
Response.Write(reader.ReadToEnd());
//Console.Write(reader.ReadToEnd());
response.Close();
}
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}
}