概述
本篇文章介绍如何使用STM32HAL库,这篇文章只要是讲如何使用mbedtls开源库,实现 1、base64编码,2、AES加解密示例。怎么样移植mbedtls开源库,请阅读我写的一篇文章《STM32HAL库-移植mbedtls开源库示例(一)》。
GitHub:https://github.com/ARMmbed/mbedtls
硬件:STM32F103CBT6最小系统板
软件:Keil 5.29 + STM32CubeMX6.01
使用前,需了解,你产品中的FLASH不能低于64K的SRAM(内存),如果你使用的比较低端的STM32,那么无解,没法用embedtls。
一、STM32CubeMx配置
注:mbedtls所使用的栈空间是比较大,STM32CubeMX生成工程代码时候将栈空间调大,如下所示:
二、Examples
main.c文件
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "mbedtls/sha1.h" //使用sha1相关加密函数
#include "string.h" //使用到了strlen函数
#include "mbedtls/aes.h"
#include "mbedtls/base64.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define ORIGINAL_DATA "ABCDEFGHIJKLMNOP"
#define PASSWORD "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDD"
#define PLAINSTRING "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//sha1编解码测试代码:
void sha1_test(void)
{
printf("mbedtls port on STM32F103 core board by champion666\r\n");
/* sha1 test */
char *source_cxt = "champion666";
char encrypt_cxt[64];
printf("source context is:%s\r\n", source_cxt);
mbedtls_sha1_context sha1_ctx;
mbedtls_sha1_init(&sha1_ctx);
mbedtls_sha1_starts(&sha1_ctx);
mbedtls_sha1_update(&sha1_ctx, (unsigned char *)source_cxt, strlen(source_cxt));
mbedtls_sha1_finish(&sha1_ctx, (unsigned char *)encrypt_cxt);
mbedtls_sha1_free(&sha1_ctx);
int i = 0;
printf("sha1 encrypt context is:[");
while (encrypt_cxt[i]) {
printf("%02x", encrypt_cxt[i]);
i++;
}
printf("]\r\n");
}
//base64编解码测试代码:
void mbedtls_base64(void)
{
int i = 0;
uint16_t len = 0;
// 原始数据
char* plaintext = ORIGINAL_DATA;
len = strlen(plaintext);
// base64编码和解码输出数据的长度
size_t enclen = 0, declen = 0;
// 存放base64编码输出
uint8_t encode[32];
// 存放base64解码输出
uint8_t decode[32];
// 编码
mbedtls_base64_encode(encode, sizeof(encode), &enclen, (unsigned char *)plaintext, len);
// 解码
mbedtls_base64_decode(decode, sizeof(decode), &declen, encode, enclen);
printf("- enclen:%d\r\n", enclen);
printf("- encode:%s\r\n", encode);
printf("- declen:%d\r\n", declen);
printf("- decode:");
for(i = 0; i < declen; i++)
{
printf("%c", (char)decode[i]);
}
printf("\r\n");
}
//AES加解密测试代码(ECB模式):
void mbedtls_aes_ecb(void)
{
int i = 0;
mbedtls_aes_context ctx;
uint16_t len = 0;
// 要加密的数据
char* plaintext = ORIGINAL_DATA;
len = strlen(plaintext);
// 密码
const uint8_t passwd[] = PASSWORD;
// 加密输出
uint8_t encrypt[len];
// 解密输出
uint8_t decrypt[len];
// 初始化
mbedtls_aes_init(&ctx);
// 设置加密密钥
mbedtls_aes_setkey_enc(&ctx, passwd, 256);
// 加密
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, (unsigned char *)plaintext, encrypt);
// 设置解密密钥
mbedtls_aes_setkey_dec(&ctx, passwd, 256);
// 解密
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_DECRYPT, encrypt, decrypt);
// 清理
mbedtls_aes_free(&ctx);
printf("data:%s\r\n", plaintext);
printf("key:%s\r\n", PASSWORD);
printf("encrypt:");
for(i = 0; i < len; i++)
{
printf("%02X", encrypt[i]);
}
printf("\r\n");
printf("decrypt:");
for(i = 0; i < len; i++)
{
printf("%c", decrypt[i]);
}
printf("\r\n");
}
//AES加解密测试代码(CBC模式):
void mbedtls_aes_cbc(void)
{
int i = 0;
mbedtls_aes_context ctx;
uint16_t len = 0;
// 密码
char* passwd = "AAAAAABBBBCCCCDD";
// 用于加密的向量表
uint8_t iv_encrypt[16] = { 0X00, 0X01, 0X02, 0X03, 0X10, 0X11, 0X12, 0X13, 0X20, 0X21, 0X22, 0X23, 0X30, 0X31, 0X32, 0X33 };
// 用于解密的向量表
uint8_t iv_decrypt[16] = { 0X00, 0X01, 0X02, 0X03, 0X10, 0X11, 0X12, 0X13, 0X20, 0X21, 0X22, 0X23, 0X30, 0X31, 0X32, 0X33 };
// 待加密的数据
char* plaintext = PLAINSTRING;
len = strlen(plaintext);
// 存储加密后的输出
uint8_t encrypt[len];
// 存储解密后的输出
uint8_t decrypt[len];
// 加密
mbedtls_aes_setkey_enc(&ctx, (unsigned char *)passwd, 128);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, len, iv_encrypt, (unsigned char *)plaintext, encrypt);
// 解密
mbedtls_aes_setkey_dec(&ctx, (unsigned char *)passwd, 128);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, len, iv_decrypt, encrypt, decrypt);
printf("data:%s\r\n", PLAINSTRING);
printf("key:%s\r\n", passwd);
// 打印出加入后的结果
printf("encrypt:");
for (i = 0; i < len; i++)
{
printf("%02X", encrypt[i]);
}
printf("\r\n");
// 打印处解密后的结果
printf("decrypt:");
for (i = 0; i < len; i++)
{
printf("%c", decrypt[i]);
}
printf("\r\n");
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
//printf("***************sha1_test()***********\r\n");
//sha1_test();
printf("***************mbedtls_base64()***********\r\n");
mbedtls_base64();
printf("***************mbedtls_aes_ecb()***********\r\n");
mbedtls_aes_ecb();
printf("***************mbedtls_aes_cbc()***********\r\n");
mbedtls_aes_cbc();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
int fgetc(FILE * f)
{
uint8_t ch = 0;
HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
三、运行结果
在线AES加密解密工具,可以验证单片机加解密是否正确。
网址1:https://the-x.cn/cryptography/Aes.aspx
网址2:http://tool.chacuo.net/cryptaes/
传送门->代码
四、总结
好了,就介绍到此。