当前位置: 编程技术>.net/c#/asp.net
C#实现https双向认证的实例代码
来源: 互联网 发布时间:2014-08-30
本文导语: 本节内容: C#实现https双向认证 操作方法,如下: 1,把浏览器中的证书导出为cer文件。 2,https 双向认证 例子: 代码示例: using System; using System.Net; using System.IO; using System.Security.Cryptography.X509Certificates; using Sys...
本节内容:
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./");
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;
}
}
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./");
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;
}
}