使用c#验证证书

时间:2016-12-12 12:48:54

标签: c# ssl https ssl-certificate

我尝试将网站与验证证书连接,但它始终会出现此错误:  "政策错误:' RemoteCertificateNameMismatch,RemoteCertificateChainErrors'"。我该如何摆脱这些错误?提前致谢。     功能如下:

protected override WebRequest GetWebRequest(Uri address)
{
   HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
   string path = @"E:\ssl_cert.pem";
   var pem = File.ReadAllText(path);

   byte[] certBuffer = GetBytesFromPEM(pem, "CERTIFICATE");
   var  certificate = new X509Certificate2(certBuffer);


   request.ClientCertificates.Add(new X509Certificate(certificate));
   return request;
}

public void Login(string loginPageAddress, string loginData)
{
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
 ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
 HttpWebRequest request = (HttpWebRequest)this.GetWebRequest(new Uri(loginPageAddress)) ;

 request.Method = "POST";
 byte[] postBytes = Encoding.ASCII.GetBytes(loginData);
 request.ContentLength = postBytes.Length;
 request.ContentType = "application/x-www-form-urlencoded";
 Stream requestStream = request.GetRequestStream();
 requestStream.Write(postBytes, 0, postBytes.Length);
 requestStream.Close();

 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 response.Close();
}

byte[]  GetBytesFromPEM(string pemString, string section)
{
    var header = String.Format("-----BEGIN {0}-----", section);
    var footer = String.Format("-----END {0}-----", section);

    var start = pemString.IndexOf(header, StringComparison.Ordinal);
    if (start < 0)
       return null;

    start += header.Length;
    var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;

    if (end < 0)
       return null;

    return Convert.FromBase64String(pemString.Substring(start, end));
}

Login("https://blablabla:12000","Username=ROOT&Pw=ROOT&submit=");

0 个答案:

没有答案