下面是一个简单的 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