ssl 使用流程是如何的(仅供参考)?

#include <QCoreApplication>

#include <chrono>
#include <thread>
#include <memory>
#include <openssl/ssl.h>

struct SSL_CTX_Deleter {
    void operator()(SSL_CTX* object) { SSL_CTX_free(object); }
};

struct SSL_Deleter {
    void operator()(SSL* object) { SSL_free(object); }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // [1]
    auto ctx = std::unique_ptr<SSL_CTX,SSL_CTX_Deleter>(SSL_CTX_new(TLS_server_method()),SSL_CTX_Deleter());

    // 设置证书
    if(SSL_CTX_use_certificate_file(ctx.get(),"cert.pem",SSL_FILETYPE_PEM) < 0){
        // error
    }

    // 设置私钥
    if(SSL_CTX_use_PrivateKey_file(ctx.get(),"cert.key",SSL_FILETYPE_PEM) < 0){
        // error
    }

    // attach fd

    // [2]
    auto ssl = std::unique_ptr<SSL,SSL_Deleter>(SSL_new(ctx.get()),SSL_Deleter());

    // [3]
    // ... socket fd
    int fd = 0;
    SSL_set_fd(ssl.get(),fd);

    // [4]
    // 服务端等待客户端握手
    SSL_accept(ssl.get());

    // 客户端连接
    // SSL_connect(ssl.get()); // 客户端需要使用这个 TLS_client_method() 函数初始化 ssl 上下文

    // [5]
    // 读取数据
    // SSL_read_ex()

    // [6]
    // 写入数据
    // SSL_write_ex()

    {
        using namespace std;
        std::thread([&a = a](){
            std::this_thread::sleep_for(3s);
            a.exit(0);
        }).detach();
    }

    return a.exec();
}

posted @ 2022-07-27 10:28  學海無涯  阅读(116)  评论(0编辑  收藏  举报