本文介绍 Ubuntu22.04 环境下 mbedtls 库的安装与使用方法。
1. mbedtls 源码下载
shell
~/ws$ git clone https://github.com/Mbed-TLS/mbedtls.git #代码克隆成功后,当前目录会生成一个 mbedtls 目录
~/ws$ cd mbedtls #进入源码目录
~/ws/mbedtls$ git submodule update --init #子模块初始化。可能会 fatal,多执行几次
~/ws/mbedtls$ cd tf-psa-crypto #进入 tf-psa-crypto 目录
~/ws/mbedtls/tf-psa-crypto$ git submodule update --init # 可能会 fatal,多执行几次
2. 编译源码
shell
~/ws/mbedtls$ mkdir build && cd build #创建并进入build目录
~/ws/mbedtls/build$ cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On .. #运行 cmake 设置编译为动态库宏(这一步会生成 Makefile)
~/ws/mbedtls/build$ make #编译。编译过程会找不到 python 模块,而报错。缺失那个就用 pip 装那个
~/ws/mbedtls/build$ sudo make install #安装动态库和头文件
~/ws/mbedtls/build$ sudo ldconfig # 之后可能会链接不到动态库,所以执行该命令
3. 测试
3.1 代码
c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mbedtls/base64.h"
#include "mbedtls/private/bignum.h"
#include "mbedtls/platform.h"
int main(int argc, char* argv[])
{
printf("hello mebedtls\n");
unsigned char date[64] = "hello world,i come from china";
unsigned char enbasestring[64];
unsigned char debasestring[64];
size_t len;
printf("date:%s\n",date);
mbedtls_base64_encode(enbasestring, 64, &len, date,strlen(date));
printf("base64:%s,len:%d\n", enbasestring, (int)len);
mbedtls_base64_decode(debasestring, 64, &len,enbasestring, strlen(enbasestring));
printf("encode string:%s,len:%d\n", debasestring, (int)len);
/// 大数
mbedtls_mpi A;
mbedtls_mpi_init(&A);
mbedtls_mpi_free(&A);
return 0;
}
3.2 编译运行
shell
yao@vela:~/mbedtls_test$ gcc test.c -o mbedtls_test -Wall -lmbedcrypto -ltfpsacrypto #编译
yao@vela:~/mbedtls_test$ ./mbedtls_test #运行
hello mebedtls
date:hello world,i come from china
base64:aGVsbG8gd29ybGQsaSBjb21lIGZyb20gY2hpbmE=,len:40
encode string:hello world,i come from china,len:29
4. 参考文档
https://mbed-tls.readthedocs.io/en/latest/kb/compiling-and-building/compiling-mbedtls-in-mingw/
https://cloud.tencent.com.cn/developer/article/1999433