From 424fda5d7bbe86c351efd1d45a29b1e6b2a3980c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Mon, 11 Feb 2013 22:05:42 +0100 Subject: [PATCH] Add ecdh_calc_secret() --- include/polarssl/ecdh.h | 13 +++++++++++++ library/ecdh.c | 17 +++++++++++++++++ tests/suites/test_suite_ecdh.function | 6 +++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/include/polarssl/ecdh.h b/include/polarssl/ecdh.h index 67d1df512..7f6f4cb28 100644 --- a/include/polarssl/ecdh.h +++ b/include/polarssl/ecdh.h @@ -149,6 +149,19 @@ int ecdh_make_public( ecdh_context *ctx, size_t *olen, int ecdh_read_public( ecdh_context *ctx, const unsigned char *buf, size_t blen ); +/** + * \brief Derive and export the shared secret + * + * \param ctx ECDH context + * \param olen number of bytes written + * \param buf destination buffer + * \param blen buffer length + * + * \return 0 if successful, or an POLARSSL_ERR_ECP_XXX error code + */ +int ecdh_calc_secret( ecdh_context *ctx, size_t *olen, + unsigned char *buf, size_t blen ); + /** * \brief Checkup routine * diff --git a/library/ecdh.c b/library/ecdh.c index dc585f47e..c04d34c42 100644 --- a/library/ecdh.c +++ b/library/ecdh.c @@ -186,6 +186,23 @@ int ecdh_read_public( ecdh_context *ctx, return ecp_tls_read_point( &ctx->grp, &ctx->Qp, &buf, blen ); } +/* + * Derive and export the shared secret + */ +int ecdh_calc_secret( ecdh_context *ctx, size_t *olen, + unsigned char *buf, size_t blen ) +{ + int ret; + + if( ( ret = ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp, &ctx->d ) ) + != 0 ) + return( ret ); + + *olen = mpi_size( &ctx->z ); + return mpi_write_binary( &ctx->z, buf, blen ); +} + + #if defined(POLARSSL_SELF_TEST) /* diff --git a/tests/suites/test_suite_ecdh.function b/tests/suites/test_suite_ecdh.function index 6f2d39937..105f99ce0 100644 --- a/tests/suites/test_suite_ecdh.function +++ b/tests/suites/test_suite_ecdh.function @@ -99,11 +99,15 @@ ecdh_exchange:id &rnd_pseudo_rand, &rnd_info ) == 0 ); TEST_ASSERT( ecdh_read_params( &cli, &vbuf, buf + len ) == 0 ); - memset( buf, 0x00, sizeof( buf ) ); vbuf = buf; + memset( buf, 0x00, sizeof( buf ) ); TEST_ASSERT( ecdh_make_public( &cli, &len, buf, 1000, &rnd_pseudo_rand, &rnd_info ) == 0 ); TEST_ASSERT( ecdh_read_public( &srv, buf, len ) == 0 ); + TEST_ASSERT( ecdh_calc_secret( &srv, &len, buf, 1000 ) == 0 ); + TEST_ASSERT( ecdh_calc_secret( &cli, &len, buf, 1000 ) == 0 ); + TEST_ASSERT( mpi_cmp_mpi( &srv.z, &cli.z ) == 0 ); + ecdh_free( &srv ); ecdh_free( &cli ); }