diff --git a/.gitignore b/.gitignore index 7805557..db3c570 100644 --- a/.gitignore +++ b/.gitignore @@ -55,6 +55,7 @@ CTestTestfile.cmake __pycache__/ *.egg-info/ dist/ +.cache/ # Virtual environment folders venv/ diff --git a/README.md b/README.md index f7bf096..217f18c 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,68 @@ -| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | -| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- | +# ESP32-C3 OTA Relay -# Wi-Fi SoftAP Example +ESP32-C3FH4 OTA 中继固件,通过 WiFi / BLE 接收上位机 OTA 固件包,通过 SPI 转发给下位机(GD32)。 -(See the README.md file in the upper level 'examples' directory for more information about examples.) +## 硬件平台 -This example shows how to use the Wi-Fi SoftAP functionality of the Wi-Fi driver of ESP for serving as an Access Point. +- **芯片:** ESP32-C3FH4 (RISC-V, 单核) +- **Flash:** 4MB +- **编译工具链:** ESP-IDF v6.0, riscv32-esp-elf -## How to use example +## 功能模块 -SoftAP supports Protected Management Frames(PMF). Necessary configurations can be set using pmf flags. Please refer [Wifi-Security](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/wifi-security.html) for more info. +| 模块 | 描述 | +|------|------| +| `health_monitor` | 温度 + 电压 + WiFi RSSI 监控 | +| `ota_relay` | OTA 数据包接收与转发 | +| `wifi_ota` | WiFi OTA 服务器 (HTTP) | +| `ble_ota` | BLE OTA 服务器 (GATT) | +| `spi_master` | SPI 主站,与下位机通信 | +| `protocol` | CRC 校验 + AES 解密 | -### Configure the project - -Open the project configuration menu (`idf.py menuconfig`). - -In the `Example Configuration` menu: - -* Set the Wi-Fi configuration. - * Set `WiFi SSID`. - * Set `WiFi Password`. - -Optional: If you need, change the other options according to your requirements. - -### Build and Flash - -Build the project and flash it to the board, then run the monitor tool to view the serial output: - -Run `idf.py -p PORT flash monitor` to build, flash and monitor the project. - -(To exit the serial monitor, type ``Ctrl-]``.) - -See the Getting Started Guide for all the steps to configure and use the ESP-IDF to build projects. - -* [ESP-IDF Getting Started Guide on ESP32](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/index.html) -* [ESP-IDF Getting Started Guide on ESP32-S2](https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/get-started/index.html) -* [ESP-IDF Getting Started Guide on ESP32-C3](https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/get-started/index.html) - -## Example Output - -There is the console output for this example: +## 目录结构 ``` -I (917) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 -I (917) wifi: mode : softAP (30:ae:a4:80:45:69) -I (917) wifi softAP: wifi_init_softap finished.SSID:myssid password:mypassword -I (26457) wifi: n:1 0, o:1 0, ap:1 1, sta:255 255, prof:1 -I (26457) wifi: station: 70:ef:00:43:96:67 join, AID=1, bg, 20 -I (26467) wifi softAP: station:70:ef:00:43:96:67 join, AID=1 -I (27657) esp_netif_lwip: DHCP server assigned IP to a station, IP is: 192.168.4.2 +main/ +├── CMakeLists.txt +├── core/main.cpp # 任务创建入口 +├── relay/ota_relay.cpp # OTA 中继逻辑 +├── transport/ +│ ├── spi_master.cpp # SPI 主站 +│ └── protocol.cpp # 协议层 (CRC/AES) +├── server/ +│ ├── wifi_ota.cpp # WiFi OTA HTTP 服务器 +│ └── ble_ota.cpp # BLE OTA GATT 服务器 +└── monitor/ + ├── health_monitor.cpp # 健康监控 + └── debug_log.cpp # UDP 调试日志 ``` -## Running the example on ESP Chips without Wi-Fi +## 任务配置 (单核 ESP32-C3) -This example can run on ESP Chips without Wi-Fi using ESP-Hosted. See the [Two-Chip Solution](../../README.md#wi-fi-examples-with-two-chip-solution) section in the upper level `README.md` for information. +所有任务固定运行在 CPU 核 0: -## Troubleshooting +| 任务 | 优先级 | 栈大小 | 说明 | +|------|--------|--------|------| +| health_mon | configMAX_PRIORITIES - 4 | 4096 | 健康监控 | +| ota_relay | configMAX_PRIORITIES - 2 | 8192 | OTA 中继 | +| wifi_ota | configMAX_PRIORITIES - 3 | 8192 | WiFi OTA | +| ble_ota | configMAX_PRIORITIES - 3 | 8192 | BLE OTA | -For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon. +## 待确认参数 + +- AES-128 主密钥 (MASTER_KEY_HERE) +- 搅伴算法种子 (SCRAMBLE_CONST_HERE) +- 芯片唯一码 (CHIP_UID_HERE) +- OTA Service UUID (需与 APP 侧协商) + +## 编译 + +```bash +idf.py set-target esp32c3 +idf.py build +idf.py flash monitor +``` + +## 调试日志 + +UDP 输出到上位机,默认 IP: `DEBUG_LOG_IP`,端口: `DEBUG_LOG_PORT`。 diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index a5c5c13..0000000 --- a/docs/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# ESP32-C3FH4 OTA Relay - -Complete firmware for ESP32-C3FH4 acting as OTA relay between APP/PC and GD32E508VET6. - -## Build - -```bash -export IDF_PATH=/path/to/esp-idf -source $IDF_PATH/export.sh -mkdir build && cd build -cmake .. -make -``` - -## Structure - -``` -main/ - main.c - Entry point, task creation - app_main.c - Application init, system monitor task - ota_relay.c - 4-stage OTA state machine - spi_master.c - SPI2 (VSPI) master driver - protocol.c - Frame format, CRC16, AES, scramble - wifi_ota.c - WiFi AP/STA + HTTP server - ble_ota.c - BLE GATT server - health_monitor.c - Temperature/voltage/WiFi monitoring -``` - -## Features - -- WiFi AP mode (SSID: ESP32_OTA_RELAY, pw: 12345678) -- BLE GATT OTA service -- HTTP POST /ota/upload for firmware -- SPI to GD32 (40MHz, GPIO4-9) -- Flash storage with断点续传 -- System health monitoring - -## TODO (confirm with GD32 team) - -- MASTER_KEY_HERE - AES-128 master key (16 bytes) -- SCRAMBLE_CONST_HERE - scramble algorithm seed -- CHIP_UID_HERE - GD32 chip unique ID -- GATT UUIDs for OTA service \ No newline at end of file diff --git a/docs/tasks.md b/docs/tasks.md deleted file mode 100644 index 8f84747..0000000 --- a/docs/tasks.md +++ /dev/null @@ -1,258 +0,0 @@ -# ESP32-C3FH4 OTA 中继 — 开发任务清单 - -> 每完成一条就在前面打 `-[x]`(手机/PC 编辑器支持 Markdown checkbox) - ---- - -## T0 — 项目基础设施 - -- [x] **T0.1** 搭建 ESP32-C3 工程 - - 基于 ESP-IDF v5.x,创建 CMake 项目骨架 - - 配置 chip=esp32c3 - -- [x] **T0.2** 配置 Flash 分区表 - - 定义 gd32_ota (256KB)、otadata、spiffs、app0、app1 分区 - -- [x] **T0.3** 配置 GPIO 引脚 - - SPI2 (VSPI) 引脚映射到 GPIO6-9 - - CS=GPIO4 - -- [x] **T0.4** FreeRTOS 任务框架 - - 建立 System Monitor / OTA Relay / WiFi Server / BLE GATT 四个任务 - - 配置任务优先级和栈大小 - -- [x] **T0.5** 日志系统 - - 统一 printf 接口 - - Flash 日志写入接口(system_log 分区) - ---- - -## T1 — SPI 通信层 - -- [x] **T1.1** SPI2 总线初始化 - - VSPI, clock=40MHz, mode=0, queue_size=1 - -- [x] **T1.2** SPI 同步读写接口 - - `spi_sync_transfer(cmd, payload, &recv_buf)` 阻塞式 - -- [x] **T1.3** 协议帧封装/解析 - - SOF (0xEB) 检测 - - CMD 路由分发 - - CRC16 Modbus 校验/生成 - -- [x] **T1.4** SPI 超时与重发 - - 发送后等待 ACK 超时 3s - - ≥3 次则报错并通知 APP - ---- - -## T2 — 安全握手与认证(阶段一) - -- [x] **T2.1** 搅伴算法实现 - - 输入:时间戳 + 内存地址 + rand - - 处理:3轮单字节 + 2轮4字节 - - 输出:16 bytes nonce_server - -- [x] **T2.2** AES 加解密实现 - - 预置主密钥,AES-128 CBC 模式 - - 使用 ESP32 mbedTLS 库 - - 实现 `aes_encrypt()` / `aes_decrypt()` - -- [x] **T2.3** 握手状态机 - - RELAY_HANDSHAKE_IDLE → HANDSHAKE_WAIT → CHALLENGE_SENT → CHALLENGE_RESPOND → SESSION_KEY_SENT → AUTH_COMPLETE - -- [x] **T2.4** 会话密钥管理 - - K_session 存储到 RAM - - 握手完成后生效,OTA 结束时清除 - ---- - -## T3 — OTA 中继核心(阶段二~四) - -- [x] **T3.1** SEND_SIZE 发送 - - 发送固件总大小 (4B LE) 给 GD32 - - 等待 0xBA C0 + seq 确认 - -- [x] **T3.2** Flash 写入接口 - - `gd32_ota_partition` 追加写入 - - 支持断点续传(追加不擦写) - -- [x] **T3.3** `ota_meta.json` 管理 - - 读写元数据:total_size / stored_size / last_seq / chunk_count - - 初始写入 / 中途更新 / 完成后校验 - -- [x] **T3.4** 固件流式转发 - - 存储完成后,从 Flash 按 48B/packet 逐包发给 GD32 - - 每包等待 GD32 ACK - -- [x] **T3.5** DATA_END 处理 - - 最后一包带 IFEND 标志 - - 发送后等待 TRANSFER_DONE (0xBA C0 + FF FF FF FF) - -- [x] **T3.6** FINISH_OTA - - 发送 0x0A AC,等待 GD32 跳转确认 - - 清理会话密钥和 RAM 缓存 - -- [x] **T3.7** 四阶段状态机整合 - - 串联 T3.1~T3.6,覆盖全部 15 个状态 - - 与 System Monitor 健康状态联动 - ---- - -## T4 — WiFi OTA 服务器 - -- [x] **T4.1** WiFi 连接管理 - - AP 模式(ESP32 作为热点) - - STA 模式(连接路由器) - - 连接失败自动重试 - -- [x] **T4.2** HTTP 服务器 - - POST `/ota/upload` 接收固件 binary - - 返回 JSON 响应:`{"status": "ok", "progress": xx}` - -- [x] **T4.3** 固件分包存储 - - 接收 APP 分包(APP→ESP32 协议:CMD + SEQ + SIZE + DATA + CRC32) - - 写入 Flash,更新 meta - -- [x] **T4.4** 存储完成后自动触发 - - 检测 `stored_size == total_size` - - 自动开始阶段一~四 - -- [x] **T4.5** 进度上报 - - HTTP 响应附带当前进度百分比 - - 存储进度实时更新 - ---- - -## T5 — BLE OTA 服务器 - -- [x] **T5.1** BLE GATT Service 创建 - - Primary Service (OTA) - - Control Point (UUID 0001): 写命令/通知 - - Data In (UUID 0002): 写无回应,大数据通道 - - Data Out (UUID 0003): Notify,透传 GD32 响应 - - Version (UUID 0004): 只读,ESP32 版本号 - -- [x] **T5.2** Control Point 写处理 - - 解析 0xF0~0xF7 命令帧 - - 转发给 OTA Relay 任务处理 - -- [x] **T5.3** Data In 大数据通道 - - 接收 APP 固件分包,写入 Flash - - 与 T3.2 / T3.3 共用存储逻辑 - -- [x] **T5.4** Data Out 通知 - - 将 GD32 ACK 透传给 APP(BLE Notify) - -- [x] **T5.5** MTU 协商 - - 设置 MTU ≥ 512 bytes - - 支持大数据分包多次写入 - ---- - -## T6 — ESP32 自检与保护 - -- [x] **T6.1** System Monitor 任务 - - FreeRTOS 高优先级任务 - - 通过 mutex 与 OTA Relay 共享 health_state - -- [x] **T6.2** 芯片温度检测 - - 使用 `esp_temp_sensor` API - - 1s 轮询,三级阈值判断(NORMAL < 80°C / WARNING 80-100°C / CRITICAL > 100°C) - -- [x] **T6.3** 供电电压检测 - - 使用 `esp_efuse` / `esp_adc` - - 5s 轮询,三级阈值判断(NORMAL 2.5-3.6V / WARNING < 2.5V / CRITICAL < 2.3V) - -- [x] **T6.4** WiFi RSSI 监测 - - `esp_wifi_sta_get_rssi()` - - 10s 轮询,三级阈值(NORMAL > -70 / WARNING -70~-85 / CRITICAL < -85 dBm) - -- [x] **T6.5** BLE 连接状态回调 - - BLE GAP Event 驱动更新连接状态 - - 断开时通知 APP 重连 - -- [x] **T6.6** 健康状态联动 - - OTA 每包发送前检查 health_state - - WARNING:降低 SPI 速率 + 记录日志 - - CRITICAL:暂停 OTA + 通知 APP - - SAFE_SHUTDOWN:发送 ABORT + 清除 meta + 保护性复位 - -- [x] **T6.7** Flash 日志写入 - - 异常事件追加写入 system_log 分区 - - 格式:`[TIMESTAMP] EVENT_TYPE: value` - ---- - -## T7 — 错误处理与恢复 - -- [x] **T7.1** GD32 超时处理 - - SPI 无响应 3s → 重发同一包 - - ≥3 次 → 报错并通知 APP - -- [x] **T7.2** CRC 重发机制 - - GD32 要求重发时,从 Flash 重新读取当前包并重发 - - 限次重试(建议 3 次),超限则中止 OTA - -- [x] **T7.3** WiFi/BLE 断连恢复 - - WiFi 断开自动重连(STA 模式) - - BLE 断开通知 APP,保留 meta 支持断点续传 - -- [x] **T7.4** OTA 中止与清理 - - SAFE_SHUTDOWN 时发送 ABORT 到 GD32 - - 清除 meta,重置状态机,释放内存 - ---- - -## T8 — 测试与验证 - -- [ ] **T8.1** SPI 回环测试 - - 短接 MOSI/MISO(GPIO7↔GPIO9) - - 自发自收验证帧协议正确性 - -- [ ] **T8.2** 协议 Mock 测试 - - 不接 GD32,用逻辑分析仪抓 SPI 数据 - - 验证 SOF/CMD/LEN/CRC16 帧格式正确 - -- [ ] **T8.3** Flash 读写验证 - - 写入 256KB 数据后读出校验 - - 确认存储逻辑正确 - -- [ ] **T8.4** 单包刷写测试 - - 发送小固件(< 1KB)给 GD32 - - 验证 GD32 写入正确 - -- [ ] **T8.5** 完整 OTA 测试 - - 传输一个完整固件(≥ 100KB) - - 验证四阶段(握手→大小→数据→结束)全流程 - -- [ ] **T8.6** 断点续传测试 - - 模拟传输中断(断开连接) - - 恢复后从断点继续,验证 meta 正确恢复 - -- [ ] **T8.7** 自检触发测试 - - 升温验证 WARNING/CRITICAL 状态正确触发 - - 降压验证 SAFE_SHUTDOWN 正确中止 OTA - ---- - -## 完成总结 - -**T0-T7 已完成代码实现:** -- T0: 项目骨架、CMake、FreeRTOS任务框架、日志系统 -- T1: SPI2 (VSPI) 40MHz master驱动、同步传输、超时重试 -- T2: 搅伴算法(3轮单字节+2轮4字节)、AES-128 CBC、握手状态机、会话密钥管理 -- T3: 四阶段OTA状态机、Flash追加写入、ota_meta.json断点续传、固件转发 -- T4: WiFi AP/STA模式、HTTP服务器(POST /ota/upload)、进度上报 -- T5: BLE GATT Service、Control Point/Data In/Data Out特性、MTU≥512 -- T6: System Monitor任务、温度/电压/WiFi RSSI三级监测、健康状态联动 -- T7: GD32超时重试、CRC重发机制、断连恢复、SAFE_SHUTDOWN中止清理 - -**待验证(T8):** -- T8.1-T8.7 需要硬件在环测试(SPI连接GD32、WiFi/BLE连接APP) - -**待确认参数(代码中已TODO标注):** -- MASTER_KEY_HERE: AES-128 主密钥(16 bytes) -- SCRAMBLE_CONST_HERE: 搅伴算法种子 -- CHIP_UID_HERE: GD32芯片唯一ID -- OTA Service UUID: 需与APP侧协商 \ No newline at end of file diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index bfcc295..076ad20 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -30,4 +30,5 @@ idf_component_register( esp_blockdev nvs_flash freertos + mbedtls ) diff --git a/main/core/main.cpp b/main/core/main.cpp index e03b2ec..66503e2 100644 --- a/main/core/main.cpp +++ b/main/core/main.cpp @@ -5,7 +5,6 @@ #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "esp_log.h" #include "esp_chip_info.h" #include "monitor/health_monitor.h" diff --git a/main/monitor/debug_log.cpp b/main/monitor/debug_log.cpp index 2927533..595775d 100644 --- a/main/monitor/debug_log.cpp +++ b/main/monitor/debug_log.cpp @@ -8,11 +8,9 @@ #include #include #include -#include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "esp_err.h" -#include "esp_netif_types.h" #include "debug_log.h" diff --git a/main/transport/protocol.cpp b/main/transport/protocol.cpp index ce5a795..d9166b8 100644 --- a/main/transport/protocol.cpp +++ b/main/transport/protocol.cpp @@ -1,349 +1,25 @@ /* * protocol.c - 协议层实现 * T2.1, T2.2, T1.3 - * ESP-IDF 6.0 适配版本 - 使用软件 AES 实现 + 硬件 RNG + * ESP-IDF 6.0 适配版本 - 使用硬件 AES-128-CBC + 硬件 RNG + * + * 加密实现使用 ESP32-C3 硬件 AES 加速器(通过 mbedtls port) */ #include +#include #include "esp_random.h" +#include "aes/esp_aes.h" #include "app_config.h" #include "protocol.h" #include "monitor/debug_log.h" static bool s_protocol_initialized = false; -// ========== 软件 AES-128 实现 ========== - -// AES S-Box -static const uint8_t sbox[256] = { - 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, - 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, - 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, - 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, - 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, - 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, - 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, - 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, - 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, - 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, - 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, - 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, - 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, - 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, - 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, - 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 -}; - -// AES 逆 S-Box -static const uint8_t rsbox[256] = { - 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, - 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, - 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, - 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, - 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, - 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, - 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, - 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, - 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, - 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, - 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, - 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, - 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, - 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, - 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, - 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d -}; - -// AES Rcon -static const uint8_t Rcon[11] = { - 0x8d,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36 -}; - -// AES 状态操作 -#define AES_BLOCK_SIZE 16 - -typedef struct { - uint8_t round_key[176]; // 10 rounds * 16 bytes + initial key -} aes128_context_t; - -// GF(2^8) 乘法 -static uint8_t gmul(uint8_t a, uint8_t b) -{ - uint8_t p = 0, hbit; - for (int i = 0; i < 8; i++) { - if (b & 1) { - p ^= a; - } - hbit = a & 0x80; - a <<= 1; - if (hbit) { - a ^= 0x1b; // 模不可约多项式 x^8 + x^4 + x^3 + x + 1 - } - b >>= 1; - } - return p; -} - -// 密钥扩展 -static void aes128_key_expansion(const uint8_t *key, aes128_context_t *ctx) -{ - uint8_t temp[4]; - memcpy(ctx->round_key, key, 16); - - for (int i = 4; i < 44; i++) { - for (int j = 0; j < 4; j++) { - temp[j] = ctx->round_key[(i - 1) * 4 + j]; - } - - if (i % 4 == 0) { - // RotWord - uint8_t t = temp[0]; - temp[0] = temp[1]; - temp[1] = temp[2]; - temp[2] = temp[3]; - temp[3] = t; - - // SubWord - temp[0] = sbox[temp[0]]; - temp[1] = sbox[temp[1]]; - temp[2] = sbox[temp[2]]; - temp[3] = sbox[temp[3]]; - - temp[0] ^= Rcon[i / 4]; - } - - for (int j = 0; j < 4; j++) { - ctx->round_key[i * 4 + j] = ctx->round_key[(i - 4) * 4 + j] ^ temp[j]; - } - } -} - -// 字节替换 -static void sub_bytes(uint8_t *state) -{ - for (int i = 0; i < 16; i++) { - state[i] = sbox[state[i]]; - } -} - -// 逆字节替换 -static void inv_sub_bytes(uint8_t *state) -{ - for (int i = 0; i < 16; i++) { - state[i] = rsbox[state[i]]; - } -} - -// 行移位 -static void shift_rows(uint8_t *state) -{ - uint8_t temp; - - // 第1行左移1位 - temp = state[1]; - state[1] = state[5]; - state[5] = state[9]; - state[9] = state[13]; - state[13] = temp; - - // 第2行左移2位 - temp = state[2]; - state[2] = state[10]; - state[10] = temp; - temp = state[6]; - state[6] = state[14]; - state[14] = temp; - - // 第3行左移3位 - temp = state[15]; - state[15] = state[11]; - state[11] = state[7]; - state[7] = state[3]; - state[3] = temp; -} - -// 逆行移位 -static void inv_shift_rows(uint8_t *state) -{ - uint8_t temp; - - // 第1行右移1位 - temp = state[13]; - state[13] = state[9]; - state[9] = state[5]; - state[5] = state[1]; - state[1] = temp; - - // 第2行右移2位 - temp = state[2]; - state[2] = state[10]; - state[10] = temp; - temp = state[6]; - state[6] = state[14]; - state[14] = temp; - - // 第3行右移3位 - temp = state[3]; - state[3] = state[7]; - state[7] = state[11]; - state[11] = state[15]; - state[15] = temp; -} - -// 列混合 -static void mix_columns(uint8_t *state) -{ - uint8_t temp[16]; - memcpy(temp, state, 16); - - for (int i = 0; i < 4; i++) { - int c = i * 4; - state[c] = gmul(2, temp[c]) ^ gmul(3, temp[c + 1]) ^ temp[c + 2] ^ temp[c + 3]; - state[c + 1] = temp[c] ^ gmul(2, temp[c + 1]) ^ gmul(3, temp[c + 2]) ^ temp[c + 3]; - state[c + 2] = temp[c] ^ temp[c + 1] ^ gmul(2, temp[c + 2]) ^ gmul(3, temp[c + 3]); - state[c + 3] = gmul(3, temp[c]) ^ temp[c + 1] ^ temp[c + 2] ^ gmul(2, temp[c + 3]); - } -} - -// 逆列混合 -static void inv_mix_columns(uint8_t *state) -{ - uint8_t temp[16]; - memcpy(temp, state, 16); - - for (int i = 0; i < 4; i++) { - int c = i * 4; - state[c] = gmul(14, temp[c]) ^ gmul(11, temp[c + 1]) ^ gmul(13, temp[c + 2]) ^ gmul(9, temp[c + 3]); - state[c + 1] = gmul(9, temp[c]) ^ gmul(14, temp[c + 1]) ^ gmul(11, temp[c + 2]) ^ gmul(13, temp[c + 3]); - state[c + 2] = gmul(13, temp[c]) ^ gmul(9, temp[c + 1]) ^ gmul(14, temp[c + 2]) ^ gmul(11, temp[c + 3]); - state[c + 3] = gmul(11, temp[c]) ^ gmul(13, temp[c + 1]) ^ gmul(9, temp[c + 2]) ^ gmul(14, temp[c + 3]); - } -} - -// 轮密钥加 -static void add_round_key(uint8_t *state, const uint8_t *round_key) -{ - for (int i = 0; i < 16; i++) { - state[i] ^= round_key[i]; - } -} - -// AES-128 加密单个块 -static void aes128_encrypt_block(const uint8_t *input, uint8_t *output, const aes128_context_t *ctx) -{ - uint8_t state[16]; - - // 复制输入到状态(列优先顺序) - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - state[i * 4 + j] = input[j * 4 + i]; - } - } - - // 初始轮密钥加 - add_round_key(state, ctx->round_key); - - // 9轮加密 - for (int round = 1; round < 10; round++) { - sub_bytes(state); - shift_rows(state); - mix_columns(state); - add_round_key(state, ctx->round_key + round * 16); - } - - // 最后一轮(无列混合) - sub_bytes(state); - shift_rows(state); - add_round_key(state, ctx->round_key + 10 * 16); - - // 复制状态到输出(列优先顺序) - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - output[j * 4 + i] = state[i * 4 + j]; - } - } -} - -// AES-128 解密单个块 -static void aes128_decrypt_block(const uint8_t *input, uint8_t *output, const aes128_context_t *ctx) -{ - uint8_t state[16]; - - // 复制输入到状态(列优先顺序) - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - state[i * 4 + j] = input[j * 4 + i]; - } - } - - // 初始轮密钥加 - add_round_key(state, ctx->round_key + 10 * 16); - - // 9轮解密 - for (int round = 9; round >= 1; round--) { - inv_shift_rows(state); - inv_sub_bytes(state); - add_round_key(state, ctx->round_key + round * 16); - inv_mix_columns(state); - } - - // 最后一轮(无逆列混合) - inv_shift_rows(state); - inv_sub_bytes(state); - add_round_key(state, ctx->round_key); - - // 复制状态到输出(列优先顺序) - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - output[j * 4 + i] = state[i * 4 + j]; - } - } -} - -// CBC 模式加密 -static void aes128_cbc_encrypt(const uint8_t *input, uint8_t *output, size_t length, - const uint8_t *iv, const aes128_context_t *ctx) -{ - uint8_t prev[16]; - memcpy(prev, iv, 16); - - for (size_t i = 0; i < length; i += 16) { - uint8_t block[16]; - memcpy(block, input + i, 16); - - // XOR with previous ciphertext (or IV for first block) - for (int j = 0; j < 16; j++) { - block[j] ^= prev[j]; - } - - aes128_encrypt_block(block, output + i, ctx); - memcpy(prev, output + i, 16); - } -} - -// CBC 模式解密 -static void aes128_cbc_decrypt(const uint8_t *input, uint8_t *output, size_t length, - const uint8_t *iv, const aes128_context_t *ctx) -{ - uint8_t prev[16]; - memcpy(prev, iv, 16); - - for (size_t i = 0; i < length; i += 16) { - aes128_decrypt_block(input + i, output + i, ctx); - - // XOR with previous ciphertext (or IV for first block) - for (int j = 0; j < 16; j++) { - output[i + j] ^= prev[j]; - } - - memcpy(prev, input + i, 16); - } -} - void protocol_init(void) { if (s_protocol_initialized) return; - DEBUG_INFO("PROT", "初始化协议层(CRC16、软件AES)..."); + DEBUG_INFO("PROT", "初始化协议层(CRC16、硬件AES-CBC)..."); s_protocol_initialized = true; DEBUG_INFO("PROT", "协议层就绪"); @@ -442,44 +118,94 @@ int frame_parse(const uint8_t *frame, size_t frame_len, return 0; } -// AES-128 CBC 加密 -// 注意: 函数名带 protocol_ 前缀以避免与 ESP-IDF wpa_supplicant 组件冲突 +// AES-128 CBC 加密(使用 ESP32-C3 硬件 AES) int protocol_aes_encrypt(const uint8_t *plaintext, size_t len, const uint8_t *key, const uint8_t *iv, uint8_t *ciphertext_out) { + if (!plaintext || !key || !iv || !ciphertext_out) { + return -1; + } + + // PKCS#7 填充 size_t padded_len = ((len + 15) / 16) * 16; uint8_t padded[256]; - + memset(padded, 0, sizeof(padded)); memcpy(padded, plaintext, len); uint8_t pad = (uint8_t)(16 - (len % 16)); + if (pad == 0) pad = 16; memset(&padded[len], pad, pad); - aes128_context_t ctx; - aes128_key_expansion(key, &ctx); - aes128_cbc_encrypt(padded, ciphertext_out, padded_len, iv, &ctx); + // 硬件 AES-CBC 加密(使用 ESP32-C3 硬件 AES 加速器) + esp_aes_context aes_ctx; + esp_aes_init(&aes_ctx); - return padded_len; + int ret = esp_aes_setkey(&aes_ctx, key, 128); + if (ret != 0) { + DEBUG_ERR("PROT", "esp_aes_setkey 失败: %d", ret); + esp_aes_free(&aes_ctx); + return -1; + } + + uint8_t iv_copy[16]; + memcpy(iv_copy, iv, 16); + + ret = esp_aes_crypt_cbc(&aes_ctx, ESP_AES_ENCRYPT, padded_len, iv_copy, padded, ciphertext_out); + + esp_aes_free(&aes_ctx); + + if (ret == 0) { + return padded_len; + } else { + DEBUG_ERR("PROT", "esp_aes_crypt_cbc 加密失败: %d", ret); + return -1; + } } -// AES-128 CBC 解密 -// 注意: 函数名带 protocol_ 前缀以避免与 ESP-IDF wpa_supplicant 组件冲突 +// AES-128 CBC 解密(使用 ESP32-C3 硬件 AES) int protocol_aes_decrypt(const uint8_t *ciphertext, size_t len, const uint8_t *key, const uint8_t *iv, uint8_t *plaintext_out) { - if (len % 16 != 0) { - DEBUG_ERR("PROT", "Ciphertext 长度不是 16 的倍数: %zu", len); + if (!ciphertext || !key || !iv || !plaintext_out) { return -1; } - aes128_context_t ctx; - aes128_key_expansion(key, &ctx); - aes128_cbc_decrypt(ciphertext, plaintext_out, len, iv, &ctx); + if (len % 16 != 0 || len == 0) { + DEBUG_ERR("PROT", "Ciphertext 长度无效: %zu", len); + return -1; + } + + // 硬件 AES-CBC 解密(使用 ESP32-C3 硬件 AES 加速器) + esp_aes_context aes_ctx; + esp_aes_init(&aes_ctx); + + int ret = esp_aes_setkey(&aes_ctx, key, 128); + if (ret != 0) { + DEBUG_ERR("PROT", "esp_aes_setkey 失败: %d", ret); + esp_aes_free(&aes_ctx); + return -1; + } + + uint8_t iv_copy[16]; + memcpy(iv_copy, iv, 16); + + ret = esp_aes_crypt_cbc(&aes_ctx, ESP_AES_DECRYPT, len, iv_copy, ciphertext, plaintext_out); + + esp_aes_free(&aes_ctx); + + if (ret != 0) { + DEBUG_ERR("PROT", "esp_aes_crypt_cbc 解密失败: %d", ret); + return -1; + } // 移除 PKCS#7 填充 uint8_t pad = plaintext_out[len - 1]; - if (pad > 16) return -1; + if (pad > 16) { + DEBUG_ERR("PROT", "无效填充: %d", pad); + return -1; + } + return len - pad; } diff --git a/main/transport/protocol.h b/main/transport/protocol.h index 637153c..112e8e2 100644 --- a/main/transport/protocol.h +++ b/main/transport/protocol.h @@ -1,7 +1,7 @@ /* * protocol.h - 帧格式、CRC16、AES 加密解密 * T2.2, T1.3 - * ESP-IDF 6.0 适配版本 - 使用软件 AES 实现 + 硬件 RNG + * ESP-IDF 6.0 适配版本 - 使用硬件 AES-128-CBC + 硬件 RNG */ #ifndef PROTOCOL_H #define PROTOCOL_H