2026-01-08 9:19 AM
At present, as of the last Hal version as far as I know, obk cannot be used in a non trust zone project.
FLASH_TYPEPROGRAM_QUADWORD_OBK fails because the NS bits aren't set, among other issues.
Is this by design, IE obk can't be used by non TZ, or is this just simply not a completed or fully fixed feature?
Here is what I'm doing
I've edited HAL_FLASHEx_Erase like
#if defined (FLASH_SR_OBKERR)
else if ((pEraseInit->TypeErase&~(FLASH_NON_SECURE_MASK)) == FLASH_TYPEERASE_OBK_ALT)
{
/* OBK erase to be done */
FLASH_OBKErase();
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_SR_OBKERR */And my code is:
int keyStorageSavePrivate(char* key) {
uint32_t status;
uint32_t len = strnlen(key, KEY_STORAGE_SIZE - 16);
int ret = 0;
static uint32_t FlashWord[4];
if (len >= KEY_STORAGE_SIZE - 16) {
return 1;
}
len += 1; // Add string 0
HAL_FLASH_Unlock();
HAL_FLASHEx_OBK_Unlock();
if (len & 0b1111) {
len &= ~(0b1111);
len += 16;
}
uint32_t Address = (uint32_t)private_key;
uint32_t EndAddress = Address + len;
const char* next = key;
static uint32_t SectorError;
static FLASH_EraseInitTypeDef EraseInitStruct;
pFlash.ProcedureOnGoing = FLASH_NON_SECURE_MASK;
FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);//Clear
EraseInitStruct.TypeErase = FLASH_TYPEERASE_OBK_ALT | FLASH_NON_SECURE_MASK;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
ret = 6;
goto lock;
}
while (Address < EndAddress) {
memcpy(FlashWord, next, 16);
status = HAL_FLASH_Program(
FLASH_TYPEPROGRAM_QUADWORD_OBK | FLASH_NON_SECURE_MASK, Address,
(uint32_t)FlashWord);
if (status == HAL_OK) {
Address = Address + 16; /* increment for the next Flash word*/
next += 16;
} else {
/* Error occurred while programming */
ret = 2;
break;
}
}
if (ret == 0) {
if (HAL_FLASHEx_OBK_Swap(FLASH_OBK_SWAP_OFFSET_ALL) != HAL_OK) {
ret = 3;
}
}
HAL_ICACHE_Invalidate();
lock:
HAL_FLASH_Lock();
HAL_FLASHEx_OBK_Lock();
if (memcmp(private_key, key, len)) {
ret = 3;
}
return ret;
}
2026-01-08 10:02 AM
2026-01-08 6:47 PM
I've looked at that link quite a few times, but the OP ended up using a secure zone to do this.
2026-01-09 1:14 AM
Hello @_EFrie ,
Please remove FLASH_NON_SECURE_MASK from your code, it should work.
This non secure mask is used only when TZ is enabled, and when executing in secure, to be able to write in non secure flash.
Best regards
Jocelyn
2026-01-09 1:37 AM
I couldn’t get it to work at all, are you sure? I just went through this with Hal. The problem is that without tweaking it tries to use the 0x5000 secure flash registers which just doesn’t write any flash.
2026-01-09 2:38 AM
Just to recap, I just went through this on regular flash, nothing would erase or write until I made sure flash_ns with 4000 base was being used. The way the obk library is presently written only uses the secure 5000 flash base.