第15章:固件安全与升级
本章将介绍ESP32固件的安全烧录和远程升级技术,确保固件在传输和运行过程中的安全性。
ESP32支持对固件进行加密烧录,防止固件被非法读取或篡改。
使用espsecure.py工具生成256位加密密钥:
espsecure.py generate_flash_encryption_key my_flash_encryption_key.bin
将生成的密钥烧录到ESP32的eFuse中:
espefuse.py --port PORT burn_key flash_encryption my_flash_encryption_key.bin
在menuconfig中启用闪存加密功能:
idf.py menuconfig
> Security features
> Enable flash encryption on boot
> Enable flash encryption in Development mode (for testing)
使用以下命令加密并烧录固件:
espsecure.py encrypt_flash_data --keyfile my_flash_encryption_key.bin --address 0x10000 -o firmware-encrypted.bin firmware.bin
esptool.py --port PORT write_flash 0x10000 firmware-encrypted.bin
OTA(Over-The-Air)升级允许设备通过网络远程更新固件,ESP32支持带签名校验的安全OTA升级。
使用espsecure.py工具生成签名密钥:
espsecure.py generate_signing_key secure_boot_signing_key.pem
对要发布的固件进行签名:
espsecure.py sign_data --keyfile secure_boot_signing_key.pem --output firmware-signed.bin firmware.bin
将签名后的固件上传到HTTP服务器,并提供版本信息文件:
// version.json 示例
{
"version": "1.2.0",
"url": "http://your-server.com/firmware-signed.bin",
"checksum": "sha256-of-firmware"
}
在ESP32应用中实现OTA升级逻辑:
#include <esp_https_ota.h>
#include <esp_ota_ops.h>
void perform_ota_update() {
esp_http_client_config_t config = {
.url = "http://your-server.com/version.json",
.cert_pem = server_cert_pem_start,
};
esp_https_ota_config_t ota_config = {
.http_config = &config,
};
esp_err_t ret = esp_https_ota(&ota_config);
if (ret == ESP_OK) {
esp_restart();
} else {
printf("OTA更新失败: %s", esp_err_to_name(ret));
}
}
在menuconfig中启用OTA签名验证:
idf.py menuconfig
> Component config
> ESP HTTPS OTA
> Enable OTA verification with RSA signature
客服小姐姐(优先添加)
讲师微信(备用)