目录
概述
本篇文章介绍如何使用STM32HAL库,针对芯片读写保护实现防篡改、破解功能(详解),本案例还包含内部FLASH读写数据,本质就是操作Flash。
硬件:STM32F103CBT6最小系统板
软件:Keil 5.29 + STM32CubeMX5.6.1
一、使用方法
通过参阅《STM32中文参考手册》得知,不同型号的芯片对应FLASH大小不一样,如下所示:
在《STM32中文参考手册》pdf文档中找到,第2.3.3小节:嵌入式闪存,对应的页数30。
这里我使用的是STM32F103CBT6的FLASH是128k,通过手册得知是属于中容量,所以只需看下面FLASH地址分配图与每一页对应的大小(字节)即可。
想更详细的了解,请阅读《STM32中文参考手册》,自行上网查找资料下载。
二、STM32CubeMx配置
三、Examples
打开STM32CubeMx生成的keil工程,新建bsp文件夹,同时分别新建bsp_flash.c与bsp_flash.h文件,并把这两个文件,添加keil工程中来即可。
添加头文件路径
1、bsp_flash.h文件
#ifndef __BSP_FLASH_H
#define __BSP_FLASH_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
#define DATASTOREADDR 0x0800F800//数据存放地址
/* Error code */
typedef enum
{
FLASHIF_OK = 0,
FLASHIF_ERASEKO,
FLASHIF_WRITINGCTRL_ERROR,
FLASHIF_WRITING_ERROR,
FLASHIF_PROTECTION_ERRROR
}Flash_Status_t;
typedef enum {
APPLICATION_NORMAL = 0, // APP能正常稳定运行
APPLICATION_UPDATED, // APP刚更新完成,等待测试启动
APPLICATION_ERROR, // APP错误,不能正常工作
}Application_Status_t;
typedef __PACKED_STRUCT{
uint32_t Device_id; // 设备号
uint32_t Hardware_Version; // 硬件版本信息
uint32_t Application_Version; // APP软件版本
uint32_t Application_Status; // APP的状态. @Application_Status_t
uint32_t SystemParamCRC;
}SystemParamTypeDef;
void Flash_Test(void);
#ifdef __cplusplus
}
#endif
#endif
2、bsp_flash.c文件
#include "bsp_flash.h"
#include "stdio.h"
#include "string.h"
HAL_StatusTypeDef FLASH_If_EnableReadProtection(void)
{
FLASH_OBProgramInitTypeDef OptionsBytesStruct = { 0 };
HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
HAL_StatusTypeDef result = HAL_OK;
if (OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_0)
{
OptionsBytesStruct.OptionType = OPTIONBYTE_RDP;
OptionsBytesStruct.RDPLevel = OB_RDP_LEVEL_1;
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
if (HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
{
/* Launch the option byte loading */
HAL_FLASH_OB_Launch();
/* Lock the FLASH Option Control Registers access */
HAL_FLASH_OB_Lock();
HAL_FLASH_Lock();
return result;
}
/* Launch the option byte loading */
HAL_FLASH_OB_Launch();
/* Lock the FLASH Option Control Registers access */
HAL_FLASH_OB_Lock();
HAL_FLASH_Lock();
result = HAL_ERROR;
}
return result;
}
HAL_StatusTypeDef Flash_If_DisableReadProtection(void)
{
FLASH_OBProgramInitTypeDef OptionsBytesStruct = { 0 };
HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
HAL_StatusTypeDef result = HAL_OK;
if (OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_1)
{
OptionsBytesStruct.OptionType = OPTIONBYTE_RDP;
OptionsBytesStruct.RDPLevel = OB_RDP_LEVEL_0;
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
if (HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
{
/* Launch the option byte loading */
HAL_FLASH_OB_Launch();
/* Lock the FLASH Option Control Registers access */
HAL_FLASH_OB_Lock();
HAL_FLASH_Lock();
return result;
}
/* Launch the option byte loading */
HAL_FLASH_OB_Launch();
/* Lock the FLASH Option Control Registers access */
HAL_FLASH_OB_Lock();
HAL_FLASH_Lock();
result = HAL_ERROR;
}
return result;
}
HAL_StatusTypeDef Set_FlashReadProtection(uint8_t mode)
{
HAL_StatusTypeDef result = HAL_ERROR;
if (mode == 1)
{
FLASH_If_EnableReadProtection();
printf("EnableReadProtection!!!\r\n");
result = HAL_OK;
}
else
{
Flash_If_DisableReadProtection();
printf("DisableReadProtection!!!\r\n");
result = HAL_OK;
}
return result;
}
void FLASH_If_Init(void)
{
/* Unlock the Program memory */
HAL_FLASH_Unlock();
/* Clear all FLASH flags */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
// /* Unlock the Program memory */
HAL_FLASH_Lock();
}
uint8_t FLASH_If_Write(uint32_t WriteAddr, uint32_t * pBuffer, uint32_t length)
{
static FLASH_EraseInitTypeDef pEraseInit;
uint32_t pageerror = 0; //定义擦除出错时,返回的Flash地址
//uint32_t* pDATA = (uint32_t*)&pBuffer;
// uint8_t page = sizeof(pBuffer) / sizeof(uint32_t);
HAL_FLASH_Unlock();
pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
pEraseInit.PageAddress = WriteAddr; //定义数据地址
pEraseInit.NbPages = 1; //定义擦除页面数 - 页 = 1024byte
// pEraseInit.Banks = FLASH_BANK_1;
HAL_FLASHEx_Erase(&pEraseInit, &pageerror); //擦除Flash
for (uint32_t i = 0; i < length; i++)
{
//HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, WriteAddr + i * 2, *(pDATA + i)); //半字节:FLASH_TYPEPROGRAM_HALFWORD
#if 0
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, WriteAddr + i * 4, *(pBuffer + i)); //字节:FLASH_TYPEPROGRAM_WORD
#else
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, WriteAddr, *(uint32_t*)(pBuffer+i)) == HAL_OK)
{
/* Check the written value */
if (*(uint32_t*)WriteAddr != *(uint32_t*)(pBuffer+i))
{
HAL_FLASH_Lock();
/* Flash content doesn't match SRAM content */
return(FLASHIF_WRITINGCTRL_ERROR);
}
/* Increment FLASH destination address */
WriteAddr += 4;
}
else
{
HAL_FLASH_Lock();
/* Error occurred while writing data in Flash memory */
return (FLASHIF_WRITING_ERROR);
}
#endif
}
HAL_FLASH_Lock();
return (FLASHIF_OK);
}
uint8_t FLASH_If_Read(uint32_t ReadAddr, uint32_t *pBuffer, uint32_t DataLength)
{
uint32_t i;
for(i = 0; i < DataLength; i++)
{
pBuffer[i] = *(__IO uint32_t*)(ReadAddr);//读取4个字节.
ReadAddr += 4;//偏移4个字节.
}
return (FLASHIF_OK);
}
void Flash_Test(void)
{
SystemParamTypeDef SystemParam_default = {
.Device_id = 0x00000111,
.Hardware_Version = 0x10000111,
.Application_Version = 0x00000111,
.Application_Status = APPLICATION_NORMAL
};
SystemParamTypeDef SystemParam_update = {
.Device_id = 0x00000222,
.Hardware_Version = 0x10000222,
.Application_Version = 0x10000222,
.Application_Status = APPLICATION_UPDATED
};
SystemParamTypeDef SystemParam_read;
uint32_t page = sizeof(SystemParam_default) / sizeof(uint32_t);
printf("Flash_Test!!!\r\n");
Set_FlashReadProtection(0);
FLASH_If_Init();
//memset(SystemParam_default, 0, sizeof(SystemParam_default)); //清空结构体内容
memset(&SystemParam_read, 0, sizeof(SystemParam_read)); //清空结构体内容
FLASH_If_Write(DATASTOREADDR, (uint32_t*)&SystemParam_default, page);
FLASH_If_Read(DATASTOREADDR, (uint32_t*)&SystemParam_read, page);
printf("Device_id:0x%08lX, Hardware_Version:0x%08lX, Application_Version:0x%08lX, Application_Status:0x%08lX \r\n",
SystemParam_read.Device_id, SystemParam_read.Hardware_Version,
SystemParam_read.Application_Version, SystemParam_read.Application_Status);
HAL_Delay(100);
printf("UPDATA!!! \r\n");
//memset(&SystemParam_default, 0, sizeof(SystemParam_default)); //清空结构体内容
memset(&SystemParam_read, 0, sizeof(SystemParam_read)); //清空结构体内容
FLASH_If_Write(DATASTOREADDR, (uint32_t*)&SystemParam_update, page);
FLASH_If_Read(DATASTOREADDR, (uint32_t*)&SystemParam_read, page);
printf("Device_id:0x%08lX, Hardware_Version:0x%08lX, Application_Version:0x%08lX, Application_Status:0x%08lX \r\n",
SystemParam_read.Device_id, SystemParam_read.Hardware_Version,
SystemParam_read.Application_Version, SystemParam_read.Application_Status);
}
3、mian.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 "bsp_flash.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* 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 */
/* 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 */
Flash_Test();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
HAL_Delay(1000);
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
/* 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****/
四、运行结果
打开读保护
只需在bsp_flash.c文件,修改这语句即可 Set_FlashReadProtection(1);
保存,编译,下载程序运行,运行结果:
再次下载,就会提示,无法下载
使用ST-Link Utility工具,解除无法下载问题
此时,连接都无法连接,莫慌。
Target-> Option Bytes…
把 Read Out Protection 中的 Enabled,改为 Disabled 即可,点击下面“Apply”按键。
擦除芯片程序
擦除成功。
传送门->
代码
(注:下载下来的代码需要修改,以博文为准,修改地方是:void Flash_Test() 函数)
五、总结
好了,就介绍到此,防止别人盗版自己所开发的产品,建议加上此功能。这种加密手段能够在一定程度上增加芯片破解难度,对抄板公司设置门槛。