kmackay / micro-ecc

ECDH and ECDSA for 8-bit, 32-bit, and 64-bit processors.
BSD 2-Clause "Simplified" License
1.26k stars 460 forks source link

mbedtls_ecdh_gen_public speed dosen't improve #219

Open kakaroot1998 opened 1 year ago

kakaroot1998 commented 1 year ago

int mbedtls_ecp_gen_keypair( mbedtls_ecp_group grp, mbedtls_mpi d, mbedtls_ecp_point Q, int (f_rng)(void , unsigned char , size_t), void *p_rng ) { ECP_VALIDATE_RET( grp != NULL ); ECP_VALIDATE_RET( d != NULL ); ECP_VALIDATE_RET( Q != NULL ); ECP_VALIDATE_RET( f_rng != NULL );

if 1

unsigned char priKey[ECDH_PRI_KEY_LEN];
unsigned char pub_key_buf[ECDH_PUB_KEY_LEN + 1];
unsigned char *pubKey = pub_key_buf + 1;

if (grp->id == MBEDTLS_ECP_DP_SECP256R1) {
    if (uECC_make_key(pubKey, priKey, uECC_secp256r1())) {
        pub_key_buf[0] = 0x04;
        mbedtls_ecp_point_read_binary(grp, Q, pub_key_buf, ECDH_PUB_KEY_LEN + 1);
        mbedtls_mpi_read_binary(d, priKey, ECDH_PRI_KEY_LEN);
        return 0;
    }
}

endif

return( mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ) );

}

use uECC_make_key to gen ecc key pair seems cost same time compared to mbedtls_ecp_gen_keypair_base but mbedtls_ecdh_compute_shared speed improves s lot;

int mbedtls_ecdh_compute_shared( mbedtls_ecp_group grp, mbedtls_mpi z, const mbedtls_ecp_point Q, const mbedtls_mpi d, int (f_rng)(void , unsigned char , size_t), void p_rng ) { ECDH_VALIDATE_RET( grp != NULL ); ECDH_VALIDATE_RET( Q != NULL ); ECDH_VALIDATE_RET( d != NULL ); ECDH_VALIDATE_RET( z != NULL );

if 1

if (grp->id == MBEDTLS_ECP_DP_SECP256R1) {
    unsigned char priKey[ECDH_PRI_KEY_LEN];
    unsigned char pub_key_buf[ECDH_PUB_KEY_LEN + 1];
    unsigned char sharedKey[ECDH_SHARED_KEY_LEN];
    unsigned char *pubKey = pub_key_buf + 1;
    size_t len;

    mbedtls_ecp_point_write_binary(grp, Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &len, pub_key_buf, sizeof(pub_key_buf));
    mbedtls_mpi_write_binary(d, priKey, ECDH_PRI_KEY_LEN);
    if (uECC_shared_secret(pubKey, priKey, sharedKey, uECC_secp256r1())) {
        mbedtls_mpi_read_binary(z, sharedKey, ECDH_SHARED_KEY_LEN);
        return 0;
    }
}

endif

return( ecdh_compute_shared_restartable( grp, z, Q, d,
                                         f_rng, p_rng, NULL ) );
kakaroot1998 commented 1 year ago

OK , i forget call the uECC_set_rng function;