使用Mbedtls库进行CMAC加密。
参考官网教程:https://mbed-tls.readthedocs.io/en/latest/getting_started/building/#building-with-cmake。
由于CMAC的使用比较简单,因此,库源码中没有Example。参考代码直接就再 cmac.c
中。照抄就好:
#include
#include
#include
#include
#include
#define KEYS_LEN 16
#define DATA_LEN 9
void printArray(uint8_t *array, int len)
{
for (int i = 0; i < len; i++) {
printf("%02x", array[i]);
}
printf("\r\n");
}
void str2hex(char *str, uint8_t *hex, int len)
{
for (int i = 0; i < len; i++) {
int number;
sscanf(str + i * 2, "%02x", &number);
hex[i] = number;
}
}
int main(int argc, char **argv)
{
int ret;
uint8_t keys[KEYS_LEN] = {0};
uint8_t data[DATA_LEN] = {0};
uint8_t output[16] = {0};
str2hex("B8B34DA2D4C4D578D8494390E3DFE7A7", keys, KEYS_LEN);
str2hex("434D41432054657374", data, DATA_LEN);
ret = mbedtls_aes_cmac_prf_128(keys, KEYS_LEN, data, DATA_LEN, output);
if (ret) {
printf("error: mbedtls_aes_cmac_prf_128: %s\r\n", mbedtls_high_level_strerr(ret));
return -1;
}
printf("keys: ");
printArray(keys, KEYS_LEN);
printf("data: ");
printArray(data, DATA_LEN);
printf("out: ");
printArray(output, 16);
}
编译:
cmake_minimum_required(VERSION 3.10)
project(cmac_test)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include_directories(./include)
link_directories(./lib)
add_executable(cmac_test cmac_test.c)
target_link_libraries(cmac_test mbedtls mbedcrypto)
CMAC在线计算。
一个参考例子:https://www.cryptopp.com/wiki/CMAC 。
两者对得上。
运行我们自己的例子:
成功