From f499993cb289964ab052b702951b1e248d7a875b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Mon, 12 Aug 2013 17:02:59 +0200 Subject: [PATCH] Add ecdsa_from_keypair() Also fix bug/limitation in mpi_copy: would segfault if src just initialised and not set to a value yet. (This case occurs when copying a context which contains only the public part of the key, eg.) --- include/polarssl/ecdsa.h | 10 ++++++++++ library/bignum.c | 6 ++++++ library/ecdsa.c | 14 ++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/include/polarssl/ecdsa.h b/include/polarssl/ecdsa.h index 15b90e667..47382e583 100644 --- a/include/polarssl/ecdsa.h +++ b/include/polarssl/ecdsa.h @@ -142,6 +142,16 @@ int ecdsa_read_signature( ecdsa_context *ctx, int ecdsa_genkey( ecdsa_context *ctx, ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +/** + * \brief Set an ECDSA context from an EC key pair + * + * \param ctx ECDSA context to set + * \param key EC key to use + * + * \return 0 on success, or a POLARSSL_ERR_ECP code. + */ +int ecdsa_from_keypair( ecdsa_context *ctx, const ecp_keypair *key ); + /** * \brief Initialize context * diff --git a/library/bignum.c b/library/bignum.c index cc4b1f368..b0bbf8f9c 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -130,6 +130,12 @@ int mpi_copy( mpi *X, const mpi *Y ) if( X == Y ) return( 0 ); + if( Y->p == NULL ) + { + mpi_free( X ); + return( 0 ); + } + for( i = Y->n - 1; i > 0; i-- ) if( Y->p[i] != 0 ) break; diff --git a/library/ecdsa.c b/library/ecdsa.c index 6746233b4..bdb356750 100644 --- a/library/ecdsa.c +++ b/library/ecdsa.c @@ -283,6 +283,20 @@ int ecdsa_genkey( ecdsa_context *ctx, ecp_group_id gid, ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); } +/* + * Set context from an ecp_keypair + */ +int ecdsa_from_keypair( ecdsa_context *ctx, const ecp_keypair *key ) +{ + int ret = ecp_group_copy( &ctx->grp, &key->grp ) || + mpi_copy( &ctx->d, &key->d ) || + ecp_copy( &ctx->Q, &key->Q ); + + if( ret != 0 ) + ecdsa_free( ctx ); + + return( ret ); +} /* * Initialize context