openssl TLS 单向认证

下面是一个简单的 C 语言程序示例,它展示了如何使用 OpenSSL 来实现基于 TLS 的加密 TCP 通信。这个程序包括一个服务器和一个客户端,它们通过 TLS 加密的 TCP 连接进行通信。

步骤概览
初始化 OpenSSL 库。
创建 SSL 上下文(SSL_CTX)。
在服务器端,加载服务器证书和私钥;在客户端,加载 CA 证书。
使用 SSL 套接字进行加密通信。
服务器端代码
c
复制代码
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 4444
#define CERT_FILE “server.crt”
#define KEY_FILE “server.key”

void handle_client(SSL *ssl) {
char buf[1024];
int bytes;

// 接收数据
bytes = SSL_read(ssl, buf, sizeof(buf));
if (bytes > 0) {
    buf[bytes] = 0;
    printf("Client message: %s\n", buf);
    
    // 发送数据
    SSL_write(ssl, "Hello from server", strlen("Hello from server"));
} else {
    ERR_print_errors_fp(stderr);
}

// 关闭 SSL 连接
SSL_shutdown(ssl);
SSL_free(ssl);

}

int main() {
SSL_CTX *ctx;
SSL *ssl;
int server_fd, client_fd;
struct sockaddr_in addr;

// 初始化 OpenSSL
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();

// 创建 SSL 上下文
ctx = SSL_CTX_new(TLS_server_method());
if (!ctx) {
    perror("Unable to create SSL context");
    ERR_print_errors_fp(stderr);
    exit(EXIT_FAILURE);
}

// 加载服务器证书和私钥
if (SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM) <= 0) {
    ERR_print_errors_fp(stderr);
    exit(EXIT_FAILURE);
}

if (SSL_CTX_use_PrivateKey_file(ctx, KEY_FIL
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值