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;
}
Solved! Go to Solution.
2026-01-20 6:07 AM
This ends up being related to the -mcmse flag being set, in Crossworks this is the `v8M Has CMSE Instructions` value. This does have the effect of not compiling in FLASH_OBK_HDPL3XX So that has to be added manually.