首页 > 解决方案 > 使用 BouncyCastle 库在 C# 中进行 HTTPS 调用

问题描述

使用 C# 4.0,我需要使用 BouncyCastle 库进行 HTTPS 调用(短故事:Windows XP + TLS 1.2)。

使用以下代码时,我收到“HTTP 错误 400。请求动词无效”。

这是我的代码:

using (var client = new TcpClient("serverName", 443))
{
    var sr = new SecureRandom();
    var cl = new MyTlsClient();
    var protocol = new TlsClientProtocol(client.GetStream(), sr);
    protocol.Connect(new MyTlsClient());

    using (var stream = protocol.Stream)
    {
         var hdr = new StringBuilder();
         hdr.AppendLine("GET /Url/WebService.asmx?wsdl HTTP/1.1");
         hdr.AppendLine("Host: serverName");
         hdr.AppendLine("Content-Type: text/xml; charset=utf-8");
         hdr.AppendLine("Connection: close");
         hdr.AppendLine();

         var dataToSend = Encoding.ASCII.GetBytes(hdr.ToString());
         sr.NextBytes(dataToSend);

         stream.Write(dataToSend, 0, dataToSend.Length);

         int totalRead = 0;
         string response = "";
         byte[] buff = new byte[1000];
         do
         {
              totalRead = stream.Read(buff, 0, buff.Length);
              response += Encoding.ASCII.GetString(buff, 0, totalRead);
         } while (totalRead == buff.Length);
     }
 } 

class MyTlsClient : DefaultTlsClient
{
    public override TlsAuthentication GetAuthentication() 
    {
        return new MyTlsAuthentication();
    }
}

class MyTlsAuthentication : TlsAuthentication
{
    public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { return null; }

    public void NotifyServerCertificate(Certificate serverCertificate) {    }
}

我已经做了什么:

有任何想法吗 ?

标签: c#-4.0httpswindows-xpbouncycastletls1.2

解决方案


感谢 PeterDettman,他给了我解决方案:

我不能使用 sr.NextBytes(instructions),所以代码变成:

using (var client = new TcpClient("serverName", 443))
{
    var sr = new SecureRandom();
    var cl = new MyTlsClient();
    var protocol = new TlsClientProtocol(client.GetStream(), sr);
    protocol.Connect(new MyTlsClient());

    using (var stream = protocol.Stream)
    {
         var hdr = new StringBuilder();
         hdr.AppendLine("GET /Url/WebService.asmx?wsdl HTTP/1.1");
         hdr.AppendLine("Host: serverName");
         hdr.AppendLine("Content-Type: text/xml; charset=utf-8");
         hdr.AppendLine("Connection: close");
         hdr.AppendLine();

         var dataToSend = Encoding.ASCII.GetBytes(hdr.ToString());

         stream.Write(dataToSend, 0, dataToSend.Length);

         int totalRead = 0;
         string response = "";
         byte[] buff = new byte[1000];
         do
         {
              totalRead = stream.Read(buff, 0, buff.Length);
              response += Encoding.ASCII.GetString(buff, 0, totalRead);
         } while (totalRead == buff.Length);
     }
 } 

推荐阅读