与升压ASIO HTTPS POST请求 [英] HTTPS POST request with boost asio

查看:195
本文介绍了与升压ASIO HTTPS POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看这个例子使HTTP POST 的要求。

我有兴趣有关使HTTPS POST请求。如何提供.CRT和.key文件的位置?是否有任何实际的例子,可能显示出异常处理呢?


解决方案

下面是一个简单的POST请求了基础。


  1. 如果你定义 DEMO_USING_SSL 你会得到SSL,否则没有SSL

  2.   ctx.set_default_verify_paths();

    设置验证路径,所以你应该(一般/通常)拿起系统根证书为可信。另外还有

      ctx.add_verify_path(...);
    ctx.add_certificate_authority(...);

    一定要看看 男人c_rehash 如果你打算使用(强大) add_verify_path 方法。


  3. 现在,你甚至可以禁用/调整证书验证。或者,确实如您在OP提到加入错误处理:

      ctx.set_verify_mode(...);
    ctx.set_verify_depth(...);ctx.set_password_callback(...); //私钥的口令
    ctx.set_verify_callback(VerifyCallback);

    在下面的例子中,我给后者


 的#define DEMO_USING_SSL
#定义BOOST_ASIO_ENABLE_HANDLER_TRACKING#包括LT&;&iostream的GT;
#包括LT&;&了iomanip GT;
#包括LT&;升压/ bind.hpp>
#包括LT&;升压/ asio.hpp>
#包括LT&;升压/ ASIO / ssl.hpp>类客户端
{
上市:
  客户端(提高:: ASIO :: io_service对象和放大器; io_service对象,
      提高:: ASIO :: SSL ::背景和放大器;的背景下,
      提高:: ASIO ::知识产权:: TCP ::解析:迭代endpoint_iterator)
    :socket_(io_service对象
#IFDEF DEMO_USING_SSL
            ,上下文)
  {
    socket_.set_verify_mode(提高:: ASIO :: SSL :: verify_peer);
    socket_.set_verify_callback(
        提高::绑定(安培;客户:: verify_certificate,为此,_1,_2));
#其他
            )
  {
      (无效)范围内;
#万一    提高:: ASIO :: async_connect(socket_.lowest_layer(),endpoint_iterator,
        提高::绑定(安培;客户:: handle_connect,为此,
          提高:: ASIO ::占位符::错误));
  }  布尔verify_certificate(布尔preverified,
      提高:: ASIO :: SSL :: verify_context&安培; CTX)
  {
      //输入的验证回调可以用来检查是证书是否
      //为presented是有效的同行。例如,RFC 2818描述了
      //参与做这HTTPS的步骤。咨询的OpenSSL
      //有关更多详细信息的文档。请注意,回调被调用一次
      //在证书链中的每个证书,从根开始
      //证书颁发机构。      //在这个例子中,我们将简单地打印证书的主题名称。
      焦炭SUBJECT_NAME [256];
      X509 *证书= X509_STORE_CTX_get_current_cert(ctx.native_handle());
      X509_NAME_oneline(X509_get_subject_name(CERT),SUBJECT_NAME,256);
      性病::法院LT&;< 验证<< SUBJECT_NAME<< \\ n;      返回preverified;
  }  无效handle_connect(常量的boost ::系统::错误_ code&安培;错误)
  {
#IFDEF DEMO_USING_SSL
      如果(!错误)
      {
          socket_.async_handshake(提高:: ASIO :: SSL :: stream_base ::客户端,
                  提高::绑定(安培;客户:: handle_handshake,为此,
                      提高:: ASIO ::占位符::错误));
      }
      其他
      {
          性病::法院LT&;< 连接失败:<<返回Error.message()&所述;&下; \\ n;
      }
#其他
      handle_handshake(错误);
#万一
  }  无效handle_handshake(常量的boost ::系统::错误_ code&安培;错误)
  {
      如果(!错误)
      {
          性病::法院LT&;< 进入的消息:;
          静态字符常量原料[] =POST / HTTP / 1.1 \\ r \\ n主机:www.example.com \\ r \\ nConnection:关闭\\ r \\ n \\ r \\ n;          static_assert(的sizeof(生)LT; = sizeof的(REQUEST_),过大);          为size_t request_length = strlen的(生);
          性病::复制(生,生+ request_length,REQUEST_);          {
              //使用该调试:
              的std :: ostream的hexos(的std :: cout.rdbuf());
              为(自动它=原料;它的原始= + request_length;!++吧)
                  hexos<<性病::十六进制<<的std ::运输及工务局局长(2)LT;<的std :: setfill(0)LT;<的std :: showbase<< ((短签名)*它)LT;< ;
              性病::法院LT&;< \\ n;
          }          提高:: ASIO :: async_write(socket_,
                  提高:: ASIO ::缓​​冲区(REQUEST_,request_length)
                  提高::绑定(安培;客户:: handle_write,为此,
                      提高:: ASIO ::占位符::错误
                      提高:: ASIO ::占位符:: bytes_transferred));
      }
      其他
      {
          性病::法院LT&;< 握手失败:&所述;&下;返回Error.message()&所述;&下; \\ n;
      }
  }  无效handle_write(常量的boost ::系统::错误_ code和;错误,
      为size_t / * * bytes_transferred /)
  {
      如果(!错误)
      {
          性病::法院LT&;< 起点阅读循环\\ N的;
          提高:: ASIO :: async_read_until(socket_,
                  //提高:: ASIO ::缓​​冲区(reply_,sizeof的(reply_))
                  reply_,'\\ n',
                  提高::绑定(安培;客户:: handle_read,为此,
                      提高:: ASIO ::占位符::错误
                      提高:: ASIO ::占位符:: bytes_transferred));
      }
      其他
      {
          性病::法院LT&;< 写失败:<<返回Error.message()&所述;&下; \\ n;
      }
  }  无效handle_read(常量的boost ::系统::错误_ code和;错误,为size_t / * * bytes_transferred /)
  {
      如果(!错误)
      {
          性病::法院LT&;< 回复:<< &安培; reply_<< \\ n;
      }
      其他
      {
          性病::法院LT&;< 读取失败:<<返回Error.message()&所述;&下; \\ n;
      }
  }私人的:
#IFDEF DEMO_USING_SSL
  提高:: ASIO :: SSL ::流<提高:: ASIO ::知识产权:: TCP ::插座>插座_;
#其他
  提高:: ASIO ::知识产权:: TCP ::插座socket_;
#万一
  焦炭REQUEST_ [1024];
  提高:: ASIO ::流缓冲reply_;
};INT主(INT ARGC,CHAR *的argv [])
{
    尝试
    {
        如果(argc个!= 3)
        {
            的std :: CERR<< 用法:客户<主机><港口> \\ N的;
            返回1;
        }        提高:: ASIO :: io_service对象io_service对象;        提高:: ASIO ::知识产权:: TCP ::解析器解析(io_service对象);
        提高:: ASIO ::知识产权:: TCP ::解析::查询查询(的argv [1],ARGV [2]);
        提高:: ASIO ::知识产权:: TCP ::解析:迭代迭代器= resolver.resolve(查询);        提高:: ASIO :: SSL ::上下文CTX(提高:: ASIO :: SSL ::背景:: sslv23);
        ctx.set_default_verify_paths();        客户端C(io_service对象,CTX,迭代器);        io_service.run();
    }
    赶上(性病::例外急症)
    {
        的std :: CERR<< 例外:<< e.what()&所述;&下; \\ n;
    }    返回0;
}

I'm looking at this example for making HTTP POST requests.

I'm interested about making an HTTPS POST request. How do I provide the location of .crt and .key file? Is there any example, possibly showing exception handling as well?

解决方案

Here's the groundwork for a simple POST request.

  1. If you define DEMO_USING_SSL you'll get SSL, otherwise no SSL
  2. The line

    ctx.set_default_verify_paths();
    

    sets the verification paths so you should (normally/usually) pick up the system root certificates as trusted. Alternatively there are

    ctx.add_verify_path(...);
    ctx.add_certificate_authority(...);
    

    Be sure to look at man c_rehash if you intend to use the (powerful) add_verify_path approach.

  3. Now, you can even disable/tweak certificate verification. Or, indeed, add error handling as you mentioned in the OP:

    ctx.set_verify_mode(...);
    ctx.set_verify_depth(...);
    
    ctx.set_password_callback(...); // for passphrases of private keys
    ctx.set_verify_callback(VerifyCallback);
    

    In the sample below, I show the latter

#define DEMO_USING_SSL
#define BOOST_ASIO_ENABLE_HANDLER_TRACKING

#include <iostream>
#include <iomanip>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

class client
{
public:
  client(boost::asio::io_service& io_service,
      boost::asio::ssl::context& context,
      boost::asio::ip::tcp::resolver::iterator endpoint_iterator)
    : socket_(io_service
#ifdef DEMO_USING_SSL
            , context)
  {
    socket_.set_verify_mode(boost::asio::ssl::verify_peer);
    socket_.set_verify_callback(
        boost::bind(&client::verify_certificate, this, _1, _2));
#else
            )
  {
      (void) context;
#endif

    boost::asio::async_connect(socket_.lowest_layer(), endpoint_iterator,
        boost::bind(&client::handle_connect, this,
          boost::asio::placeholders::error));
  }

  bool verify_certificate(bool preverified,
      boost::asio::ssl::verify_context& ctx)
  {
      // The verify callback can be used to check whether the certificate that is
      // being presented is valid for the peer. For example, RFC 2818 describes
      // the steps involved in doing this for HTTPS. Consult the OpenSSL
      // documentation for more details. Note that the callback is called once
      // for each certificate in the certificate chain, starting from the root
      // certificate authority.

      // In this example we will simply print the certificate's subject name.
      char subject_name[256];
      X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
      X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
      std::cout << "Verifying " << subject_name << "\n";

      return preverified;
  }

  void handle_connect(const boost::system::error_code& error)
  {
#ifdef DEMO_USING_SSL
      if (!error)
      {
          socket_.async_handshake(boost::asio::ssl::stream_base::client,
                  boost::bind(&client::handle_handshake, this,
                      boost::asio::placeholders::error));
      }
      else
      {
          std::cout << "Connect failed: " << error.message() << "\n";
      }
#else
      handle_handshake(error);
#endif
  }

  void handle_handshake(const boost::system::error_code& error)
  {
      if (!error)
      {
          std::cout << "Enter message: ";
          static char const raw[] = "POST / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n";

          static_assert(sizeof(raw)<=sizeof(request_), "too large");

          size_t request_length = strlen(raw);
          std::copy(raw, raw+request_length, request_);

          {
              // used this for debugging:
              std::ostream hexos(std::cout.rdbuf());
              for(auto it = raw; it != raw+request_length; ++it)
                  hexos << std::hex << std::setw(2) << std::setfill('0') << std::showbase << ((short unsigned) *it) << " ";
              std::cout << "\n";
          }

          boost::asio::async_write(socket_,
                  boost::asio::buffer(request_, request_length),
                  boost::bind(&client::handle_write, this,
                      boost::asio::placeholders::error,
                      boost::asio::placeholders::bytes_transferred));
      }
      else
      {
          std::cout << "Handshake failed: " << error.message() << "\n";
      }
  }

  void handle_write(const boost::system::error_code& error,
      size_t /*bytes_transferred*/)
  {
      if (!error)
      {
          std::cout << "starting read loop\n";
          boost::asio::async_read_until(socket_,
                  //boost::asio::buffer(reply_, sizeof(reply_)),
                  reply_, '\n',
                  boost::bind(&client::handle_read, this,
                      boost::asio::placeholders::error,
                      boost::asio::placeholders::bytes_transferred));
      }
      else
      {
          std::cout << "Write failed: " << error.message() << "\n";
      }
  }

  void handle_read(const boost::system::error_code& error, size_t /*bytes_transferred*/)
  {
      if (!error)
      {
          std::cout << "Reply: " << &reply_ << "\n";
      }
      else
      {
          std::cout << "Read failed: " << error.message() << "\n";
      }
  }

private:
#ifdef DEMO_USING_SSL
  boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_;
#else
  boost::asio::ip::tcp::socket socket_;
#endif
  char request_[1024];
  boost::asio::streambuf reply_;
};

int main(int argc, char* argv[])
{
    try
    {
        if (argc != 3)
        {
            std::cerr << "Usage: client <host> <port>\n";
            return 1;
        }

        boost::asio::io_service io_service;

        boost::asio::ip::tcp::resolver resolver(io_service);
        boost::asio::ip::tcp::resolver::query query(argv[1], argv[2]);
        boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);

        boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
        ctx.set_default_verify_paths();

        client c(io_service, ctx, iterator);

        io_service.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

这篇关于与升压ASIO HTTPS POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆