编写一个基于mbedtls建立tls连接通信的代码示例
时间: 2023-12-10 14:50:02 浏览: 129
以下是一个基于mbedtls建立TLS连接通信的代码示例,示例中使用了mbedtls的客户端模式:
```c
#include "mbedtls/net_sockets.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include <stdio.h>
#include <string.h>
#define SERVER_NAME "example.com"
#define SERVER_PORT "443"
int main()
{
int ret;
mbedtls_net_context server_fd;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
char buf[1024];
// 初始化各种上下文
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_entropy_init(&entropy);
// 生成随机数种子
ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
if (ret != 0) {
printf("mbedtls_ctr_drbg_seed failed: %d\n", ret);
goto cleanup;
}
// 连接服务器
ret = mbedtls_net_connect(&server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP);
if (ret != 0) {
printf("mbedtls_net_connect failed: %d\n", ret);
goto cleanup;
}
// 初始化 SSL 上下文
ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0) {
printf("mbedtls_ssl_config_defaults failed: %d\n", ret);
goto cleanup;
}
// 设置主机名和端口号
ret = mbedtls_ssl_set_hostname(&ssl, SERVER_NAME);
if (ret != 0) {
printf("mbedtls_ssl_set_hostname failed: %d\n", ret);
goto cleanup;
}
// 设置 SSL 上下文
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
mbedtls_ssl_set_rng(&ssl, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
// 建立 TLS 连接
ret = mbedtls_ssl_handshake(&ssl);
if (ret != 0) {
printf("mbedtls_ssl_handshake failed: %d\n", ret);
goto cleanup;
}
// 发送数据
ret = mbedtls_ssl_write(&ssl, "Hello, world!", strlen("Hello, world!"));
if (ret < 0) {
printf("mbedtls_ssl_write failed: %d\n", ret);
goto cleanup;
}
// 接收数据
do {
ret = mbedtls_ssl_read(&ssl, buf, sizeof(buf) - 1);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
continue;
} else if (ret <= 0) {
printf("mbedtls_ssl_read failed: %d\n", ret);
goto cleanup;
}
buf[ret] = '\0';
printf("%s", buf);
} while (ret > 0);
cleanup:
mbedtls_ssl_close_notify(&ssl);
mbedtls_ssl_session_reset(&ssl);
mbedtls_net_free(&server_fd);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
return ret;
}
```
在此示例中,我们首先初始化各种上下文,然后生成随机数种子。接着,我们连接到服务器并初始化SSL上下文。在设置主机名和端口号之后,我们设置SSL上下文并建立TLS连接。最后,我们发送一条消息并接收来自服务器的响应。最后,我们清理并释放所有的上下文。
阅读全文