Page 1 of 1

Placing string at a certain address in flash

Posted: Wed Apr 27, 2022 7:46 pm
by rtborg
Hi,

Is it possible to place a const char * at a certain known address in flash, and the use the SPI flash API to erase/write the same address?

My application embeds SSL keys in the flash as const char *, however I need to provide a way for the end user to update the certificates manually. I am thinking of placing a `key.pem` file on the SD card, and then on boot the application can use its contents to overwrite the existing key in the flash.

That will cover the situation where for some reason the certificate is invalid and the device cannot receive OTA with updated certificate.

It would be great to hear other suggestions as well.

Re: Placing string at a certain address in flash

Posted: Thu Apr 28, 2022 2:00 am
by ESP_Sprite
Suggest not to do that:
- You'd need to erase the 4K block that the keys reside in, then write back the data 'around' the keys. Power loss while writing = dead device.
- You'd need to recalculate the checksum and SHA/MD5 keys of the binary if you change it. This is also pretty hairy to do.

Instead, the go-to way would be either to use NVS for this, or to use a separate partition. NVS is way easier to implement and is resistant to power loss issues. A separate partition is something you can mmap() so in case the keys are large, you don't have to spend ram on loading them.

Re: Placing string at a certain address in flash

Posted: Thu Apr 28, 2022 4:52 am
by rtborg
Using NVS was my first thought also, but I could not figure how to update the public keys with OTA in this case. Any thoughts on that?

Re: Placing string at a certain address in flash

Posted: Thu Apr 28, 2022 5:19 am
by ESP_Sprite
Most easy way would be to also have a hardcoded set of keys in the OTA, plus some kind of ID number indicating the version of keys. As soon as you start up, you check if the version in NVS is lower than in your OTA, and if so, copy/paste the key from the OTA to NVS and update the NVS version. If not, you let it be. That way, you can update NVS afterwards (and the program will not overwrite that because the version is still the same) and later in an OTA update overwrite that (as the version in the OTA is newer).

Re: Placing string at a certain address in flash

Posted: Thu Apr 28, 2022 9:14 am
by rtborg
That's a great solution - thank you very much for the suggestion.