Fix issue exporting generated key to raw intermediate buffer

* Used bignum helper API instead of memcpy
* changed the key length output to the size of the curve because:
  - using the bignum produces a bigger size than the curve size
    due to the limb size being 8 bytes and import key rejects
    the key if it's not exactly curve size.
  - we know that the generated key is filled with leading
    zeros becuase the generated key is bounded by the modulas.
* skipped leading zeros when passing the buffer to import_key()
  due to the intermediate buffer allocated to the maximum size
  possible and import_key() needs the exact size.

Signed-off-by: Waleed Elmelegy <waleed.elmelegy@arm.com>
This commit is contained in:
Waleed Elmelegy 2024-11-13 13:11:47 +00:00
parent bd36c4746a
commit a47b82c20a
2 changed files with 9 additions and 4 deletions

View File

@ -8192,12 +8192,15 @@ psa_status_t psa_generate_key_iop_complete(
}
status = mbedtls_psa_generate_key_iop_complete(&operation->ctx, key_data,
MBEDTLS_ECP_MAX_BYTES, &key_len);
sizeof(key_data), &key_len);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_import_key(&operation->attributes, key_data, key_len, key);
status = psa_import_key(&operation->attributes,
key_data + (sizeof(key_data) - key_len),
key_len,
key);
exit:
if (status != PSA_OPERATION_INCOMPLETE) {

View File

@ -634,11 +634,13 @@ psa_status_t mbedtls_psa_generate_key_iop_complete(
operation->num_ops = 1;
*key_len = operation->ecp.d.n * sizeof(mbedtls_mpi_uint);
*key_len = PSA_BITS_TO_BYTES(operation->ecp.grp.nbits);
if (*key_len > key_output_size) {
return PSA_ERROR_BUFFER_TOO_SMALL;
}
memcpy(key_output, operation->ecp.d.p, *key_len);
mbedtls_mpi_write_binary(&operation->ecp.d, key_output, key_output_size);
return mbedtls_to_psa_error(status);
}