2424#include "settings.h"
2525#include "pb_gatt_srv.h"
2626
27+ #include "mbedtls/ecdh.h"
28+
2729static void send_pub_key (void );
2830static void pub_key_ready (const uint8_t * pkey );
2931
@@ -295,6 +297,63 @@ static void prov_dh_key_cb(const uint8_t dhkey[BT_DH_KEY_LEN])
295297 dh_key_gen_complete ();
296298}
297299
300+
301+ static int
302+ mbedtls_rand (void * arg , unsigned char * buf , size_t size )
303+ {
304+ return bt_rand (arg , size );
305+ }
306+
307+ int bt_mesh_dhkey_gen (const uint8_t * remote_pk , const uint8_t * private_key_be ,
308+ uint8_t * dhkey )
309+ {
310+ int ret ;
311+ mbedtls_ecp_group group ;
312+ mbedtls_ecp_point pub_key ;
313+ mbedtls_mpi priv_key ;
314+ mbedtls_mpi z ;
315+ uint8_t uncompressed_pk [65 ];
316+
317+ mbedtls_ecp_group_init (& group );
318+ mbedtls_ecp_point_init (& pub_key );
319+ mbedtls_mpi_init (& priv_key );
320+ mbedtls_mpi_init (& z );
321+
322+ ret = mbedtls_ecp_group_load (& group , MBEDTLS_ECP_DP_SECP256R1 );
323+ if (ret != 0 ) {
324+ goto done ;
325+ }
326+
327+ uncompressed_pk [0 ] = 0x04 ;
328+ memcpy (& uncompressed_pk [1 ], remote_pk , 64 );
329+
330+ ret = mbedtls_ecp_point_read_binary (& group , & pub_key , uncompressed_pk , 65 );
331+ if (ret != 0 ) {
332+ goto done ;
333+ }
334+
335+ ret = mbedtls_mpi_read_binary (& priv_key , private_key_be , 32 );
336+ if (ret != 0 ) {
337+ goto done ;
338+ }
339+
340+ ret = mbedtls_ecdh_compute_shared (& group , & z , & pub_key , & priv_key ,
341+ mbedtls_rand , NULL );
342+ if (ret != 0 ) {
343+ goto done ;
344+ }
345+
346+ ret = mbedtls_mpi_write_binary (& z , dhkey , 32 );
347+
348+ done :
349+ mbedtls_mpi_free (& z );
350+ mbedtls_mpi_free (& priv_key );
351+ mbedtls_ecp_point_free (& pub_key );
352+ mbedtls_ecp_group_free (& group );
353+
354+ return ret ;
355+ }
356+
298357static void prov_dh_key_gen (void )
299358{
300359 const uint8_t * remote_pk ;
@@ -303,11 +362,9 @@ static void prov_dh_key_gen(void)
303362 remote_pk = bt_mesh_prov_link .conf_inputs .pub_key_provisioner ;
304363 if (MYNEWT_VAL (BLE_MESH_PROV_OOB_PUBLIC_KEY ) &&
305364 atomic_test_bit (bt_mesh_prov_link .flags , OOB_PUB_KEY )) {
306- if (uECC_valid_public_key (remote_pk , & curve_secp256r1 )) {
307- BT_ERR ("Public key is not valid" );
308- } else if (uECC_shared_secret (remote_pk , bt_mesh_prov -> private_key_be ,
309- bt_mesh_prov_link .dhkey ,
310- & curve_secp256r1 ) != TC_CRYPTO_SUCCESS ) {
365+
366+ if (bt_mesh_dhkey_gen (remote_pk , bt_mesh_prov -> private_key_be ,
367+ bt_mesh_prov_link .dhkey )) {
311368 BT_ERR ("DHKey generation failed" );
312369 } else {
313370 dh_key_gen_complete ();
0 commit comments