Thank you for this really helpful post. If anyone comes here using STM32 and looking for an equivalent implementation using ST’s CubeMX Crypto library this worked for me (apologies it’s not very polished - I’m just prototyping image signing ATM as an exploratory task for a firmware port). There’s no printf yet - so I blink the led to indicate error.
/* Initialize cryptographic library */
cmox_init_arg_t init_target = {CMOX_INIT_TARGET_L4, NULL};
if (cmox_initialize(&init_target) != CMOX_INIT_SUCCESS){
LED_blink_loop(10);
}
/* Compute the SHA256 digest of the image */
retval = cmox_hash_compute(CMOX_SHA256_ALGO, /* Use SHA256 algorithm */
(const uint8_t *)FLASH_BASE, (size_t)image_size, /* Message to digest */
computed_hash, /* Data buffer to receive digest data */
CMOX_SHA256_SIZE, /* Expected digest size */
&computed_size); /* Size of computed digest */
/* Verify API returned value of expected size*/
if ((retval != CMOX_HASH_SUCCESS) || (computed_size != CMOX_SHA256_SIZE)){
LED_blink_loop(11);
}
/* Verify matching SHA256 hash */
if (memcmp(image_hdr.image_hash, computed_hash, computed_size) != 0) {
LED_blink_loop(8);
}
/* Verify ECDSA signature */
// See STM32CubeExpansion_Crypto_V4.5.0\Projects\NUCLEO-L476RG\Applications\ECC\ECDSA_SignVerify\Src
/* Construct a ECC context, specifying mathematics implementation and working buffer for later processing */
/* Note: CMOX_ECC256_MATH_FUNCS refer to the default mathematics implementation
* selected in cmox_default_config.h. To use a specific implementation, user can
* directly choose:
* - CMOX_MATH_FUNCS_SMALL to select the mathematics small implementation
* - CMOX_MATH_FUNCS_FAST to select the mathematics fast implementation
* - CMOX_MATH_FUNCS_SUPERFAST256 to select the mathematics fast implementation optimized for 256 bits computation
*/
cmox_ecc_construct(&Ecc_Ctx, CMOX_ECC256_MATH_FUNCS, Working_Buffer, sizeof(Working_Buffer));
/* Verify the signature */
ecc_retval = cmox_ecdsa_verify(&Ecc_Ctx, /* ECC context */
CMOX_ECC_CURVE_SECP256K1, /* SECP256R1 ECC curve selected */
Public_Key, sizeof(Public_Key), /* Public key for verification */
computed_hash, CMOX_SHA256_SIZE, /* Digest to verify */
image_hdr.ecdsa_sig, CMOX_ECC_SECP256K1_SIG_LEN, /* Signature value */
&fault_check); /* Fault check variable:
to ensure no fault injection occurs during this API call */
/* Verify API returned value */
if (ecc_retval != CMOX_ECC_AUTH_SUCCESS)
{
LED_blink_loop(9);
}
// Success if we get to here