Add test utility function: wrap_as_opaque()
The new function is not tested here, but will be in a subsequent PR.
diff --git a/library/pk.c b/library/pk.c
index c34ab7e..989ed09 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -41,6 +41,10 @@
#include "mbedtls/ecdsa.h"
#endif
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#include "mbedtls/psa_util.h"
+#endif
+
#include <limits.h>
#include <stdint.h>
@@ -535,4 +539,65 @@
return( ctx->pk_info->type );
}
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/*
+ * Load the key to a PSA key slot,
+ * then turn the PK context into a wrapper for that key slot.
+ *
+ * Currently only works for EC private keys.
+ */
+int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk,
+ psa_key_slot_t *slot,
+ psa_algorithm_t hash_alg )
+{
+#if !defined(MBEDTLS_ECP_C)
+ return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
+#else
+ psa_key_slot_t key;
+ const mbedtls_ecp_keypair *ec;
+ unsigned char d[MBEDTLS_ECP_MAX_BYTES];
+ size_t d_len;
+ psa_ecc_curve_t curve_id;
+ psa_key_type_t key_type;
+ psa_key_policy_t policy;
+ int ret;
+
+ /* export the private key material in the format PSA wants */
+ if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_ECKEY )
+ return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
+
+ ec = mbedtls_pk_ec( *pk );
+ d_len = ( ec->grp.nbits + 7 ) / 8;
+ if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 )
+ return( ret );
+
+ curve_id = mbedtls_ecp_curve_info_from_grp_id( ec->grp.id )->tls_id;
+
+ /* find a free key slot */
+ if( PSA_SUCCESS != mbedtls_psa_get_free_key_slot( &key ) )
+ return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
+
+ /* set policy */
+ psa_key_policy_init( &policy );
+ psa_key_policy_set_usage( &policy, PSA_KEY_USAGE_SIGN,
+ PSA_ALG_ECDSA(hash_alg) );
+ if( PSA_SUCCESS != psa_set_key_policy( key, &policy ) )
+ return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
+
+ /* import private key in slot */
+ key_type = PSA_KEY_TYPE_ECC_KEYPAIR(curve_id);
+ if( PSA_SUCCESS != psa_import_key( key, key_type, d, d_len ) )
+ return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
+
+ /* remember slot number to be destroyed later by caller */
+ *slot = key;
+
+ /* make PK context wrap the key slot */
+ mbedtls_pk_free( pk );
+ mbedtls_pk_init( pk );
+
+ return( mbedtls_pk_setup_opaque( pk, key ) );
+#endif /* MBEDTLS_ECP_C */
+}
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
#endif /* MBEDTLS_PK_C */