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>
diff --git a/tf-psa-crypto/core/psa_crypto.c b/tf-psa-crypto/core/psa_crypto.c
index 40617b4..5a11b2b 100644
--- a/tf-psa-crypto/core/psa_crypto.c
+++ b/tf-psa-crypto/core/psa_crypto.c
@@ -8192,12 +8192,15 @@
}
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) {
diff --git a/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c b/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c
index cce993c..82e8736 100644
--- a/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c
+++ b/tf-psa-crypto/drivers/builtin/src/psa_crypto_ecp.c
@@ -634,11 +634,13 @@
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);
}