Failing to implement HAL_PKA_ECCCompleteAddition correctly
Hi,
I am struggling to get `HAL_PKA_ECCCompleteAddition` implemented correctly, that is, if I'm comparing the projective coordinates with a reference implementation, the results don't match. Same goes for converting the projective coordinates back to affine coordinates using `HAL_PKA_ECCProjective2Affine`.
I am using a STM32u585vi microprocessor, and was able to use `HAL_PKA_ECCMul` properly already.
See below the function that shows incorrect results. Could you please provide help to proceed here?
ps. In its current form, the projective X coordinate produces equal results as a C# BountyCastle reference implementation.
bool ecc_secp256r1_add_points_projective(const generator_point_t* p1, const generator_point_t* p2, generator_point_t* pOut) {
const uint8_t Z_projective_input[prime256v1_Prime_len] = {[0] = 0, [31] = 1};
uint8_t X[prime256v1_Prime_len];
uint8_t Y[prime256v1_Prime_len];
uint8_t Z[prime256v1_Prime_len];
PKA_ECCCompleteAdditionInTypeDef eccAddInput = {
.modulusSize = prime256v1_Prime_len,
.modulus = prime256v1_Prime, // Curve prime
.coefA = prime256v1_absA, /* PKA operation need abs(a) */
.coefSign = prime256v1_A_sign, // Coefficient sign
.basePointX1 = p1->x,
.basePointY1 = p1->y,
.basePointZ1 = Z_projective_input,
.basePointX2 = p2->x,
.basePointY2 = p2->y,
.basePointZ2 = Z_projective_input,
};
if (HAL_PKA_ECCCompleteAddition(&hpka, &eccAddInput, HAL_MAX_DELAY) != HAL_OK) {
return false;
}
PKA_ECCCompleteAdditionOutTypeDef eccAddOutput = {
.ptX = X,
.ptY = Y,
.ptZ = Z,
};
HAL_PKA_ECCCompleteAddition_GetResult(&hpka, &eccAddOutput);
// This is an effort to convert the coordinates manually, which failed, and I want to use the hardware acceleration
// if (ecc_convert_to_affine(X, Y, Z, pOut->x, pOut->y) == false) {
// return false;
// }
{
PKA_MontgomeryParamInTypeDef montgomeryParamIn = {
.size = prime256v1_Prime_len,
.pOp1 = prime256v1_Prime,
};
if (HAL_PKA_MontgomeryParam(&hpka, &montgomeryParamIn, HAL_MAX_DELAY) != HAL_OK) {
return false;
}
}
uint32_t montgomeryparam[8] = {0};
HAL_PKA_MontgomeryParam_GetResult(&hpka, montgomeryparam);
/**
After performing the ECC addition or other operations, we need to normalize the resulting point from
projective coordinates to affine coordinates.
*/
{
PKA_ECCProjective2AffineInTypeDef eccNormalizeInput = {
.modulusSize = prime256v1_Prime_len,
.modulus = prime256v1_Prime, /*!< pointer to curve modulus value p */
.basePointX = X, /*!< pointer to curve base point coordinate x */
.basePointY = Y, /*!< pointer to curve base point coordinate y */
.basePointZ = Z, /*!< pointer to curve base point coordinate z */
.pMontgomeryParam = montgomeryparam, // secp256r1_R2_mod_p,
};
HAL_PKA_ECCProjective2Affine(&hpka, &eccNormalizeInput, HAL_MAX_DELAY);
PKA_ECCProjective2AffineOutTypeDef eccNormalizeOutput = {
.ptX = pOut->x,
.ptY = pOut->y,
};
HAL_PKA_ECCProjective2Affine_GetResult(&hpka, &eccNormalizeOutput);
return true;
}
}
