Merged support for Camellia-GCM + ciphersuite and fixes to cipher layer
diff --git a/ChangeLog b/ChangeLog
index d9f3edb..c15c2ab 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,17 @@
 PolarSSL ChangeLog (Sorted per branch, date)
 
+= PolarSSL 1.3 branch
+Features
+   * PK tests added to test framework
+   * Added optional optimization for NIST MODP curves (POLARSSL_ECP_NIST_OPTIM)
+   * Support for Camellia-GCM mode and ciphersuites
+
+Bugfix
+   * More stringent checks in cipher layer
+   * Server does not send out extensions not advertised by client
+   * Prevent possible alignment warnings on casting from char * to 'aligned *'
+   * Misc fixes and additions to dependency checks
+
 = PolarSSL 1.3.1 released on 2013-10-15
 Features
    * Support for Brainpool curves and TLS ciphersuites (RFC 7027)
diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h
index b1c43b7..eae15e0 100644
--- a/include/polarssl/bignum.h
+++ b/include/polarssl/bignum.h
@@ -128,6 +128,7 @@
 #define POLARSSL_HAVE_UDBL
 #else
   #if ( defined(_MSC_VER) && defined(_M_AMD64) )
+    #define POLARSSL_HAVE_INT64
     typedef  int64_t t_sint;
     typedef uint64_t t_uint;
   #else
@@ -137,11 +138,13 @@
           defined(__ia64__)  || defined(__alpha__)     || \
           (defined(__sparc__) && defined(__arch64__))  || \
           defined(__s390x__) ) )
+       #define POLARSSL_HAVE_INT64
        typedef  int64_t t_sint;
        typedef uint64_t t_uint;
        typedef unsigned int t_udbl __attribute__((mode(TI)));
        #define POLARSSL_HAVE_UDBL
     #else
+       #define POLARSSL_HAVE_INT32
        typedef  int32_t t_sint;
        typedef uint32_t t_uint;
        #if ( defined(_MSC_VER) && defined(_M_IX86) )
diff --git a/include/polarssl/config.h b/include/polarssl/config.h
index 934e1fa..a631a4a 100644
--- a/include/polarssl/config.h
+++ b/include/polarssl/config.h
@@ -261,6 +261,17 @@
 #define POLARSSL_ECP_DP_BP512R1_ENABLED
 
 /**
+ * \def POLARSSL_ECP_NIST_OPTIM
+ *
+ * Enable specific 'modulo p' routines for each NIST prime.
+ * Depending on the prime and architecture, makes operations 4 to 8 times
+ * faster on the corresponding curve.
+ *
+ * Comment this macro to disable NIST curves optimisation.
+ */
+#define POLARSSL_ECP_NIST_OPTIM
+
+/**
  * \def POLARSSL_KEY_EXCHANGE_PSK_ENABLED
  *
  * Enable the PSK based ciphersuite modes in SSL / TLS.
@@ -681,7 +692,7 @@
  *
  * Enable support for TLS 1.2.
  *
- * Requires: POLARSSL_SHA256_C or POLARSSL_SHA512_C
+ * Requires: POLARSSL_SHA1_C or POLARSSL_SHA256_C or POLARSSL_SHA512_C
  *           (Depends on ciphersuites)
  *
  * Comment this macro to disable support for TLS 1.2
@@ -1001,6 +1012,8 @@
  * Module:  library/certs.c
  * Caller:
  *
+ * Requires: POLARSSL_PEM_PARSE_C
+ *
  * This module is used for testing (ssl_client/server).
  */
 #define POLARSSL_CERTS_C
@@ -1795,14 +1808,18 @@
 /*
  * Sanity checks on defines and dependencies
  */
-#if defined(POLARSSL_DHM_C) && !defined(POLARSSL_BIGNUM_C)
-#error "POLARSSL_DHM_C defined, but not all prerequisites"
+#if defined(POLARSSL_CERTS_C) && !defined(POLARSSL_PEM_PARSE_C)
+#error "POLARSSL_CERTS_C defined, but not all prerequisites"
 #endif
 
 #if defined(POLARSSL_CTR_DRBG_C) && !defined(POLARSSL_AES_C)
 #error "POLARSSL_CTR_DRBG_C defined, but not all prerequisites"
 #endif
 
+#if defined(POLARSSL_DHM_C) && !defined(POLARSSL_BIGNUM_C)
+#error "POLARSSL_DHM_C defined, but not all prerequisites"
+#endif
+
 #if defined(POLARSSL_ECDH_C) && !defined(POLARSSL_ECP_C)
 #error "POLARSSL_ECDH_C defined, but not all prerequisites"
 #endif
@@ -1814,15 +1831,15 @@
 #error "POLARSSL_ECDSA_C defined, but not all prerequisites"
 #endif
 
-#if defined(POLARSSL_ECP_C) && !defined(POLARSSL_BIGNUM_C) || ( \
-    !defined(POLARSSL_ECP_DP_SECP192R1_ENABLED) &&              \
-    !defined(POLARSSL_ECP_DP_SECP224R1_ENABLED) &&              \
-    !defined(POLARSSL_ECP_DP_SECP256R1_ENABLED) &&              \
-    !defined(POLARSSL_ECP_DP_SECP384R1_ENABLED) &&              \
-    !defined(POLARSSL_ECP_DP_SECP521R1_ENABLED) &&              \
-    !defined(POLARSSL_ECP_DP_BP256R1_ENABLED)   &&              \
-    !defined(POLARSSL_ECP_DP_BP384R1_ENABLED)   &&              \
-    !defined(POLARSSL_ECP_DP_BP512R1_ENABLED) )
+#if defined(POLARSSL_ECP_C) && ( !defined(POLARSSL_BIGNUM_C) || (   \
+    !defined(POLARSSL_ECP_DP_SECP192R1_ENABLED) &&                  \
+    !defined(POLARSSL_ECP_DP_SECP224R1_ENABLED) &&                  \
+    !defined(POLARSSL_ECP_DP_SECP256R1_ENABLED) &&                  \
+    !defined(POLARSSL_ECP_DP_SECP384R1_ENABLED) &&                  \
+    !defined(POLARSSL_ECP_DP_SECP521R1_ENABLED) &&                  \
+    !defined(POLARSSL_ECP_DP_BP256R1_ENABLED)   &&                  \
+    !defined(POLARSSL_ECP_DP_BP384R1_ENABLED)   &&                  \
+    !defined(POLARSSL_ECP_DP_BP512R1_ENABLED) ) )
 #error "POLARSSL_ECP_C defined, but not all prerequisites"
 #endif
 
@@ -1920,6 +1937,26 @@
 #error "POLARSSL_RSA_C defined, but not all prerequisites"
 #endif
 
+#if defined(POLARSSL_SSL_PROTO_SSL3) && ( !defined(POLARSSL_MD5_C) ||     \
+    !defined(POLARSSL_SHA1_C) )
+#error "POLARSSL_SSL_PROTO_SSL3 defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_SSL_PROTO_TLS1) && ( !defined(POLARSSL_MD5_C) ||     \
+    !defined(POLARSSL_SHA1_C) )
+#error "POLARSSL_SSL_PROTO_TLS1 defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_SSL_PROTO_TLS1_1) && ( !defined(POLARSSL_MD5_C) ||     \
+    !defined(POLARSSL_SHA1_C) )
+#error "POLARSSL_SSL_PROTO_TLS1_1 defined, but not all prerequisites"
+#endif
+
+#if defined(POLARSSL_SSL_PROTO_TLS1_2) && ( !defined(POLARSSL_SHA1_C) &&     \
+    !defined(POLARSSL_SHA256_C) && !defined(POLARSSL_SHA512_C) )
+#error "POLARSSL_SSL_PROTO_TLS1_2 defined, but not all prerequisites"
+#endif
+
 #if defined(POLARSSL_SSL_CLI_C) && !defined(POLARSSL_SSL_TLS_C)
 #error "POLARSSL_SSL_CLI_C defined, but not all prerequisites"
 #endif
diff --git a/include/polarssl/ecp.h b/include/polarssl/ecp.h
index 7940b32..02f6f93 100644
--- a/include/polarssl/ecp.h
+++ b/include/polarssl/ecp.h
@@ -187,6 +187,24 @@
 const ecp_curve_info *ecp_curve_list( void );
 
 /**
+ * \brief           Get curve information from an internal group identifier
+ *
+ * \param grp_id    A POLARSSL_ECP_DP_XXX value
+ *
+ * \return          The associated curve information or NULL
+ */
+const ecp_curve_info *ecp_curve_info_from_grp_id( ecp_group_id grp_id );
+
+/**
+ * \brief           Get curve information from a TLS NamedCurve value
+ *
+ * \param grp_id    A POLARSSL_ECP_DP_XXX value
+ *
+ * \return          The associated curve information or NULL
+ */
+const ecp_curve_info *ecp_curve_info_from_tls_id( uint16_t tls_id );
+
+/**
  * \brief           Initialize a point (as zero)
  */
 void ecp_point_init( ecp_point *pt );
@@ -217,25 +235,6 @@
 void ecp_keypair_free( ecp_keypair *key );
 
 /**
- * \brief           Set a point to zero
- *
- * \param pt        Destination point
- *
- * \return          0 if successful,
- *                  POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
- */
-int ecp_set_zero( ecp_point *pt );
-
-/**
- * \brief           Tell if a point is zero
- *
- * \param pt        Point to test
- *
- * \return          1 if point is zero, 0 otherwise
- */
-int ecp_is_zero( ecp_point *pt );
-
-/**
  * \brief           Copy the contents of point Q into P
  *
  * \param P         Destination point
@@ -258,6 +257,25 @@
 int ecp_group_copy( ecp_group *dst, const ecp_group *src );
 
 /**
+ * \brief           Set a point to zero
+ *
+ * \param pt        Destination point
+ *
+ * \return          0 if successful,
+ *                  POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
+ */
+int ecp_set_zero( ecp_point *pt );
+
+/**
+ * \brief           Tell if a point is zero
+ *
+ * \param pt        Point to test
+ *
+ * \return          1 if point is zero, 0 otherwise
+ */
+int ecp_is_zero( ecp_point *pt );
+
+/**
  * \brief           Import a non-zero point from two ASCII strings
  *
  * \param P         Destination point
@@ -271,25 +289,6 @@
                            const char *x, const char *y );
 
 /**
- * \brief           Import an ECP group from null-terminated ASCII strings
- *
- * \param grp       Destination group
- * \param radix     Input numeric base
- * \param p         Prime modulus of the base field
- * \param b         Constant term in the equation
- * \param gx        The generator's X coordinate
- * \param gy        The generator's Y coordinate
- * \param n         The generator's order
- *
- * \return          0 if successful, or a POLARSSL_ERR_MPI_XXX error code
- *
- * \note            Sets all fields except modp.
- */
-int ecp_group_read_string( ecp_group *grp, int radix,
-                           const char *p, const char *b,
-                           const char *gx, const char *gy, const char *n);
-
-/**
  * \brief           Export a point into unsigned binary data
  *
  * \param grp       Group to which the point should belong
@@ -327,6 +326,58 @@
                            const unsigned char *buf, size_t ilen );
 
 /**
+ * \brief           Import a point from a TLS ECPoint record
+ *
+ * \param grp       ECP group used
+ * \param pt        Destination point
+ * \param buf       $(Start of input buffer)
+ * \param len       Buffer length
+ *
+ * \return          O if successful,
+ *                  POLARSSL_ERR_MPI_XXX if initialization failed
+ *                  POLARSSL_ERR_ECP_BAD_INPUT_DATA if input is invalid
+ */
+int ecp_tls_read_point( const ecp_group *grp, ecp_point *pt,
+                        const unsigned char **buf, size_t len );
+
+/**
+ * \brief           Export a point as a TLS ECPoint record
+ *
+ * \param grp       ECP group used
+ * \param pt        Point to export
+ * \param format    Export format
+ * \param olen      length of data written
+ * \param buf       Buffer to write to
+ * \param blen      Buffer length
+ *
+ * \return          0 if successful,
+ *                  or POLARSSL_ERR_ECP_BAD_INPUT_DATA
+ *                  or POLARSSL_ERR_ECP_BUFFER_TOO_SMALL
+ */
+int ecp_tls_write_point( const ecp_group *grp, const ecp_point *pt,
+                         int format, size_t *olen,
+                         unsigned char *buf, size_t blen );
+
+/**
+ * \brief           Import an ECP group from null-terminated ASCII strings
+ *
+ * \param grp       Destination group
+ * \param radix     Input numeric base
+ * \param p         Prime modulus of the base field
+ * \param b         Constant term in the equation
+ * \param gx        The generator's X coordinate
+ * \param gy        The generator's Y coordinate
+ * \param n         The generator's order
+ *
+ * \return          0 if successful, or a POLARSSL_ERR_MPI_XXX error code
+ *
+ * \note            Sets all fields except modp.
+ */
+int ecp_group_read_string( ecp_group *grp, int radix,
+                           const char *p, const char *b,
+                           const char *gx, const char *gy, const char *n);
+
+/**
  * \brief           Set a group using well-known domain parameters
  *
  * \param grp       Destination group
@@ -369,57 +420,6 @@
                          unsigned char *buf, size_t blen );
 
 /**
- * \brief           Get curve information from an internal group identifier
- *
- * \param grp_id    A POLARSSL_ECP_DP_XXX value
- *
- * \return          The associated curve information or NULL
- */
-const ecp_curve_info *ecp_curve_info_from_grp_id( ecp_group_id grp_id );
-
-/**
- * \brief           Get curve information from a TLS NamedCurve value
- *
- * \param grp_id    A POLARSSL_ECP_DP_XXX value
- *
- * \return          The associated curve information or NULL
- */
-const ecp_curve_info *ecp_curve_info_from_tls_id( uint16_t tls_id );
-
-/**
- * \brief           Import a point from a TLS ECPoint record
- *
- * \param grp       ECP group used
- * \param pt        Destination point
- * \param buf       $(Start of input buffer)
- * \param len       Buffer length
- *
- * \return          O if successful,
- *                  POLARSSL_ERR_MPI_XXX if initialization failed
- *                  POLARSSL_ERR_ECP_BAD_INPUT_DATA if input is invalid
- */
-int ecp_tls_read_point( const ecp_group *grp, ecp_point *pt,
-                        const unsigned char **buf, size_t len );
-
-/**
- * \brief           Export a point as a TLS ECPoint record
- *
- * \param grp       ECP group used
- * \param pt        Point to export
- * \param format    Export format
- * \param olen      length of data written
- * \param buf       Buffer to write to
- * \param blen      Buffer length
- *
- * \return          0 if successful,
- *                  or POLARSSL_ERR_ECP_BAD_INPUT_DATA
- *                  or POLARSSL_ERR_ECP_BUFFER_TOO_SMALL
- */
-int ecp_tls_write_point( const ecp_group *grp, const ecp_point *pt,
-                         int format, size_t *olen,
-                         unsigned char *buf, size_t blen );
-
-/**
  * \brief           Addition: R = P + Q
  *
  * \param grp       ECP group
diff --git a/include/polarssl/ssl.h b/include/polarssl/ssl.h
index fbcbbea..01cc455 100644
--- a/include/polarssl/ssl.h
+++ b/include/polarssl/ssl.h
@@ -344,6 +344,13 @@
 #define TLS_EXT_RENEGOTIATION_INFO      0xFF01
 
 /*
+ * TLS extension flags (for extensions with outgoing ServerHello content
+ * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
+ * of state of the renegotiation flag, so no indicator is required)
+ */
+#define TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0)
+
+/*
  * Size defines
  */
 #if !defined(POLARSSL_MPI_MAX_SIZE)
@@ -547,6 +554,7 @@
     int resume;                         /*!<  session resume indicator*/
     int max_major_ver;                  /*!< max. major version client*/
     int max_minor_ver;                  /*!< max. minor version client*/
+    int cli_exts;                       /*!< client extension presence*/
 
 #if defined(POLARSSL_SSL_SESSION_TICKETS)
     int new_session_ticket;             /*!< use NewSessionTicket?    */
diff --git a/include/polarssl/ssl_ciphersuites.h b/include/polarssl/ssl_ciphersuites.h
index 27dcf3f..3a8f697 100644
--- a/include/polarssl/ssl_ciphersuites.h
+++ b/include/polarssl/ssl_ciphersuites.h
@@ -230,6 +230,7 @@
 #endif
 
 int ssl_ciphersuite_uses_ec( const ssl_ciphersuite_t *info );
+int ssl_ciphersuite_uses_psk( const ssl_ciphersuite_t *info );
 
 #ifdef __cplusplus
 }
diff --git a/include/polarssl/x509_crt.h b/include/polarssl/x509_crt.h
index 0c1b9e1..a556676 100644
--- a/include/polarssl/x509_crt.h
+++ b/include/polarssl/x509_crt.h
@@ -400,6 +400,7 @@
 int x509write_crt_set_basic_constraints( x509write_cert *ctx,
                                          int is_ca, int max_pathlen );
 
+#if defined(POLARSSL_SHA1_C)
 /**
  * \brief           Set the subjectKeyIdentifier extension for a CRT
  *                  Requires that x509write_crt_set_subject_key() has been
@@ -421,6 +422,7 @@
  * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
  */
 int x509write_crt_set_authority_key_identifier( x509write_cert *ctx );
+#endif /* POLARSSL_SHA1_C */
 
 /**
  * \brief           Set the Key Usage Extension flags
diff --git a/library/ecdsa.c b/library/ecdsa.c
index 91777ec..f653748 100644
--- a/library/ecdsa.c
+++ b/library/ecdsa.c
@@ -291,12 +291,14 @@
  */
 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 );
+    int ret;
 
-    if( ret != 0 )
+    if( ( ret = ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||
+        ( ret = mpi_copy( &ctx->d, &key->d ) ) != 0 ||
+        ( ret = ecp_copy( &ctx->Q, &key->Q ) ) != 0 )
+    {
         ecdsa_free( ctx );
+    }
 
     return( ret );
 }
diff --git a/library/ecp.c b/library/ecp.c
index d3880be..bedb675 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -112,6 +112,42 @@
 }
 
 /*
+ * Get the curve info for the internal identifer
+ */
+const ecp_curve_info *ecp_curve_info_from_grp_id( ecp_group_id grp_id )
+{
+    const ecp_curve_info *curve_info;
+
+    for( curve_info = ecp_curve_list();
+         curve_info->grp_id != POLARSSL_ECP_DP_NONE;
+         curve_info++ )
+    {
+        if( curve_info->grp_id == grp_id )
+            return( curve_info );
+    }
+
+    return( NULL );
+}
+
+/*
+ * Get the curve info from the TLS identifier
+ */
+const ecp_curve_info *ecp_curve_info_from_tls_id( uint16_t tls_id )
+{
+    const ecp_curve_info *curve_info;
+
+    for( curve_info = ecp_curve_list();
+         curve_info->grp_id != POLARSSL_ECP_DP_NONE;
+         curve_info++ )
+    {
+        if( curve_info->tls_id == tls_id )
+            return( curve_info );
+    }
+
+    return( NULL );
+}
+
+/*
  * Initialize (the components of) a point
  */
 void ecp_point_init( ecp_point *pt )
@@ -201,6 +237,29 @@
 }
 
 /*
+ * Copy the contents of a point
+ */
+int ecp_copy( ecp_point *P, const ecp_point *Q )
+{
+    int ret;
+
+    MPI_CHK( mpi_copy( &P->X, &Q->X ) );
+    MPI_CHK( mpi_copy( &P->Y, &Q->Y ) );
+    MPI_CHK( mpi_copy( &P->Z, &Q->Z ) );
+
+cleanup:
+    return( ret );
+}
+
+/*
+ * Copy the contents of a group object
+ */
+int ecp_group_copy( ecp_group *dst, const ecp_group *src )
+{
+    return ecp_use_known_dp( dst, src->id );
+}
+
+/*
  * Set point to zero
  */
 int ecp_set_zero( ecp_point *pt )
@@ -224,29 +283,6 @@
 }
 
 /*
- * Copy the contents of Q into P
- */
-int ecp_copy( ecp_point *P, const ecp_point *Q )
-{
-    int ret;
-
-    MPI_CHK( mpi_copy( &P->X, &Q->X ) );
-    MPI_CHK( mpi_copy( &P->Y, &Q->Y ) );
-    MPI_CHK( mpi_copy( &P->Z, &Q->Z ) );
-
-cleanup:
-    return( ret );
-}
-
-/*
- * Copy the contents of a group object
- */
-int ecp_group_copy( ecp_group *dst, const ecp_group *src )
-{
-    return ecp_use_known_dp( dst, src->id );
-}
-
-/*
  * Import a non-zero point from ASCII strings
  */
 int ecp_point_read_string( ecp_point *P, int radix,
@@ -263,50 +299,6 @@
 }
 
 /*
- * Import an ECP group from ASCII strings, general case (A used)
- */
-static int ecp_group_read_string_gen( ecp_group *grp, int radix,
-                           const char *p, const char *a, const char *b,
-                           const char *gx, const char *gy, const char *n)
-{
-    int ret;
-
-    MPI_CHK( mpi_read_string( &grp->P, radix, p ) );
-    MPI_CHK( mpi_read_string( &grp->A, radix, a ) );
-    MPI_CHK( mpi_read_string( &grp->B, radix, b ) );
-    MPI_CHK( ecp_point_read_string( &grp->G, radix, gx, gy ) );
-    MPI_CHK( mpi_read_string( &grp->N, radix, n ) );
-
-    grp->pbits = mpi_msb( &grp->P );
-    grp->nbits = mpi_msb( &grp->N );
-
-cleanup:
-    if( ret != 0 )
-        ecp_group_free( grp );
-
-    return( ret );
-}
-
-/*
- * Import an ECP group from ASCII strings, case A == -3
- */
-int ecp_group_read_string( ecp_group *grp, int radix,
-                           const char *p, const char *b,
-                           const char *gx, const char *gy, const char *n)
-{
-    int ret;
-
-    MPI_CHK( ecp_group_read_string_gen( grp, radix, p, "00", b, gx, gy, n ) );
-    MPI_CHK( mpi_add_int( &grp->A, &grp->P, -3 ) );
-
-cleanup:
-    if( ret != 0 )
-        ecp_group_free( grp );
-
-    return( ret );
-}
-
-/*
  * Export a point into unsigned binary data (SEC1 2.3.3)
  */
 int ecp_point_write_binary( const ecp_group *grp, const ecp_point *P,
@@ -449,150 +441,48 @@
 }
 
 /*
- * Wrapper around fast quasi-modp functions, with fall-back to mpi_mod_mpi.
- * See the documentation of struct ecp_group.
+ * Import an ECP group from ASCII strings, general case (A used)
  */
-static int ecp_modp( mpi *N, const ecp_group *grp )
+static int ecp_group_read_string_gen( ecp_group *grp, int radix,
+                           const char *p, const char *a, const char *b,
+                           const char *gx, const char *gy, const char *n)
 {
     int ret;
 
-    if( grp->modp == NULL )
-        return( mpi_mod_mpi( N, N, &grp->P ) );
+    MPI_CHK( mpi_read_string( &grp->P, radix, p ) );
+    MPI_CHK( mpi_read_string( &grp->A, radix, a ) );
+    MPI_CHK( mpi_read_string( &grp->B, radix, b ) );
+    MPI_CHK( ecp_point_read_string( &grp->G, radix, gx, gy ) );
+    MPI_CHK( mpi_read_string( &grp->N, radix, n ) );
 
-    if( mpi_cmp_int( N, 0 ) < 0 || mpi_msb( N ) > 2 * grp->pbits )
-        return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );
-
-    MPI_CHK( grp->modp( N ) );
-
-    while( mpi_cmp_int( N, 0 ) < 0 )
-        MPI_CHK( mpi_add_mpi( N, N, &grp->P ) );
-
-    while( mpi_cmp_mpi( N, &grp->P ) >= 0 )
-        MPI_CHK( mpi_sub_mpi( N, N, &grp->P ) );
+    grp->pbits = mpi_msb( &grp->P );
+    grp->nbits = mpi_msb( &grp->N );
 
 cleanup:
+    if( ret != 0 )
+        ecp_group_free( grp );
+
     return( ret );
 }
 
-#if defined(POLARSSL_ECP_DP_SECP192R1_ENABLED)
 /*
- * 192 bits in terms of t_uint
+ * Import an ECP group from ASCII strings, case A == -3
  */
-#define P192_SIZE_INT   ( 192 / CHAR_BIT / sizeof( t_uint ) )
-
-/*
- * Table to get S1, S2, S3 of FIPS 186-3 D.2.1:
- * -1 means let this chunk be 0
- * a positive value i means A_i.
- */
-#define P192_CHUNKS         3
-#define P192_CHUNK_CHAR     ( 64 / CHAR_BIT )
-#define P192_CHUNK_INT      ( P192_CHUNK_CHAR / sizeof( t_uint ) )
-
-const signed char p192_tbl[][P192_CHUNKS] = {
-    { -1,   3,  3   }, /* S1 */
-    { 4,    4,  -1  }, /* S2 */
-    { 5,    5,  5   }, /* S3 */
-};
-
-/*
- * Fast quasi-reduction modulo p192 (FIPS 186-3 D.2.1)
- */
-static int ecp_mod_p192( mpi *N )
+int ecp_group_read_string( ecp_group *grp, int radix,
+                           const char *p, const char *b,
+                           const char *gx, const char *gy, const char *n)
 {
     int ret;
-    unsigned char i, j, offset;
-    signed char chunk;
-    mpi tmp, acc;
-    t_uint tmp_p[P192_SIZE_INT], acc_p[P192_SIZE_INT + 1];
 
-    tmp.s = 1;
-    tmp.n = sizeof( tmp_p ) / sizeof( tmp_p[0] );
-    tmp.p = tmp_p;
-
-    acc.s = 1;
-    acc.n = sizeof( acc_p ) / sizeof( acc_p[0] );
-    acc.p = acc_p;
-
-    MPI_CHK( mpi_grow( N, P192_SIZE_INT * 2 ) );
-
-    /*
-     * acc = T
-     */
-    memset( acc_p, 0, sizeof( acc_p ) );
-    memcpy( acc_p, N->p, P192_CHUNK_CHAR * P192_CHUNKS );
-
-    for( i = 0; i < sizeof( p192_tbl ) / sizeof( p192_tbl[0] ); i++)
-    {
-        /*
-         * tmp = S_i
-         */
-        memset( tmp_p, 0, sizeof( tmp_p ) );
-        for( j = 0, offset = P192_CHUNKS - 1; j < P192_CHUNKS; j++, offset-- )
-        {
-            chunk = p192_tbl[i][j];
-            if( chunk >= 0 )
-                memcpy( tmp_p + offset * P192_CHUNK_INT,
-                        N->p + chunk * P192_CHUNK_INT,
-                        P192_CHUNK_CHAR );
-        }
-
-        /*
-         * acc += tmp
-         */
-        MPI_CHK( mpi_add_abs( &acc, &acc, &tmp ) );
-    }
-
-    MPI_CHK( mpi_copy( N, &acc ) );
+    MPI_CHK( ecp_group_read_string_gen( grp, radix, p, "00", b, gx, gy, n ) );
+    MPI_CHK( mpi_add_int( &grp->A, &grp->P, -3 ) );
 
 cleanup:
+    if( ret != 0 )
+        ecp_group_free( grp );
+
     return( ret );
 }
-#endif /* POLARSSL_ECP_DP_SECP192R1_ENABLED */
-
-#if defined(POLARSSL_ECP_DP_SECP521R1_ENABLED)
-/*
- * Size of p521 in terms of t_uint
- */
-#define P521_SIZE_INT   ( 521 / CHAR_BIT / sizeof( t_uint ) + 1 )
-
-/*
- * Bits to keep in the most significant t_uint
- */
-#if defined(POLARSS_HAVE_INT8)
-#define P521_MASK       0x01
-#else
-#define P521_MASK       0x01FF
-#endif
-
-/*
- * Fast quasi-reduction modulo p521 (FIPS 186-3 D.2.5)
- */
-static int ecp_mod_p521( mpi *N )
-{
-    int ret;
-    t_uint Mp[P521_SIZE_INT];
-    mpi M;
-
-    if( N->n < P521_SIZE_INT )
-        return( 0 );
-
-    memset( Mp, 0, P521_SIZE_INT * sizeof( t_uint ) );
-    memcpy( Mp, N->p, P521_SIZE_INT * sizeof( t_uint ) );
-    Mp[P521_SIZE_INT - 1] &= P521_MASK;
-
-    M.s = 1;
-    M.n = P521_SIZE_INT;
-    M.p = Mp;
-
-    MPI_CHK( mpi_shift_r( N, 521 ) );
-
-    MPI_CHK( mpi_add_abs( N, N, &M ) );
-
-cleanup:
-    return( ret );
-}
-#endif /* POLARSSL_ECP_DP_SECP521R1_ENABLED */
 
 /*
  * Domain parameters for secp192r1
@@ -739,6 +629,15 @@
     "AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308" \
     "70553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069"
 
+#if defined(POLARSSL_ECP_NIST_OPTIM)
+/* Forward declarations */
+static int ecp_mod_p192( mpi * );
+static int ecp_mod_p224( mpi * );
+static int ecp_mod_p256( mpi * );
+static int ecp_mod_p384( mpi * );
+static int ecp_mod_p521( mpi * );
+#endif
+
 /*
  * Set a group using well-known domain parameters
  */
@@ -750,7 +649,9 @@
     {
 #if defined(POLARSSL_ECP_DP_SECP192R1_ENABLED)
         case POLARSSL_ECP_DP_SECP192R1:
+#if defined(POLARSSL_ECP_NIST_OPTIM)
             grp->modp = ecp_mod_p192;
+#endif
             return( ecp_group_read_string( grp, 16,
                         SECP192R1_P, SECP192R1_B,
                         SECP192R1_GX, SECP192R1_GY, SECP192R1_N ) );
@@ -758,6 +659,9 @@
 
 #if defined(POLARSSL_ECP_DP_SECP224R1_ENABLED)
         case POLARSSL_ECP_DP_SECP224R1:
+#if defined(POLARSSL_ECP_NIST_OPTIM)
+            grp->modp = ecp_mod_p224;
+#endif
             return( ecp_group_read_string( grp, 16,
                         SECP224R1_P, SECP224R1_B,
                         SECP224R1_GX, SECP224R1_GY, SECP224R1_N ) );
@@ -765,6 +669,9 @@
 
 #if defined(POLARSSL_ECP_DP_SECP256R1_ENABLED)
         case POLARSSL_ECP_DP_SECP256R1:
+#if defined(POLARSSL_ECP_NIST_OPTIM)
+            grp->modp = ecp_mod_p256;
+#endif
             return( ecp_group_read_string( grp, 16,
                         SECP256R1_P, SECP256R1_B,
                         SECP256R1_GX, SECP256R1_GY, SECP256R1_N ) );
@@ -772,6 +679,9 @@
 
 #if defined(POLARSSL_ECP_DP_SECP384R1_ENABLED)
         case POLARSSL_ECP_DP_SECP384R1:
+#if defined(POLARSSL_ECP_NIST_OPTIM)
+            grp->modp = ecp_mod_p384;
+#endif
             return( ecp_group_read_string( grp, 16,
                         SECP384R1_P, SECP384R1_B,
                         SECP384R1_GX, SECP384R1_GY, SECP384R1_N ) );
@@ -779,7 +689,9 @@
 
 #if defined(POLARSSL_ECP_DP_SECP521R1_ENABLED)
         case POLARSSL_ECP_DP_SECP521R1:
+#if defined(POLARSSL_ECP_NIST_OPTIM)
             grp->modp = ecp_mod_p521;
+#endif
             return( ecp_group_read_string( grp, 16,
                         SECP521R1_P, SECP521R1_B,
                         SECP521R1_GX, SECP521R1_GY, SECP521R1_N ) );
@@ -878,39 +790,37 @@
 }
 
 /*
- * Get the curve info from the TLS identifier
+ * Wrapper around fast quasi-modp functions, with fall-back to mpi_mod_mpi.
+ * See the documentation of struct ecp_group.
+ *
+ * This function is in the critial loop for ecp_mul, so pay attention to perf.
  */
-const ecp_curve_info *ecp_curve_info_from_tls_id( uint16_t tls_id )
+static int ecp_modp( mpi *N, const ecp_group *grp )
 {
-    const ecp_curve_info *curve_info;
+    int ret;
 
-    for( curve_info = ecp_curve_list();
-         curve_info->grp_id != POLARSSL_ECP_DP_NONE;
-         curve_info++ )
+    if( grp->modp == NULL )
+        return( mpi_mod_mpi( N, N, &grp->P ) );
+
+    /* N->s < 0 is a much faster test, which fails only if N is 0 */
+    if( ( N->s < 0 && mpi_cmp_int( N, 0 ) != 0 ) ||
+        mpi_msb( N ) > 2 * grp->pbits )
     {
-        if( curve_info->tls_id == tls_id )
-            return( curve_info );
+        return( POLARSSL_ERR_ECP_BAD_INPUT_DATA );
     }
 
-    return( NULL );
-}
+    MPI_CHK( grp->modp( N ) );
 
-/*
- * Get the curve info for the internal identifer
- */
-const ecp_curve_info *ecp_curve_info_from_grp_id( ecp_group_id grp_id )
-{
-    const ecp_curve_info *curve_info;
+    /* N->s < 0 is a much faster test, which fails only if N is 0 */
+    while( N->s < 0 && mpi_cmp_int( N, 0 ) != 0 )
+        MPI_CHK( mpi_add_mpi( N, N, &grp->P ) );
 
-    for( curve_info = ecp_curve_list();
-         curve_info->grp_id != POLARSSL_ECP_DP_NONE;
-         curve_info++ )
-    {
-        if( curve_info->grp_id == grp_id )
-            return( curve_info );
-    }
+    while( mpi_cmp_mpi( N, &grp->P ) >= 0 )
+        /* we known P, N and the result are positive */
+        MPI_CHK( mpi_sub_abs( N, N, &grp->P ) );
 
-    return( NULL );
+cleanup:
+    return( ret );
 }
 
 /*
@@ -930,17 +840,20 @@
 
 /*
  * Reduce a mpi mod p in-place, to use after mpi_sub_mpi
+ * N->s < 0 is a very fast test, which fails only if N is 0
  */
 #define MOD_SUB( N )                                \
-    while( mpi_cmp_int( &N, 0 ) < 0 )               \
+    while( N.s < 0 && mpi_cmp_int( &N, 0 ) != 0 )   \
         MPI_CHK( mpi_add_mpi( &N, &N, &grp->P ) )
 
 /*
- * Reduce a mpi mod p in-place, to use after mpi_add_mpi and mpi_mul_int
+ * Reduce a mpi mod p in-place, to use after mpi_add_mpi and mpi_mul_int.
+ * We known P, N and the result are positive, so sub_abs is correct, and
+ * a bit faster.
  */
 #define MOD_ADD( N )                                \
     while( mpi_cmp_mpi( &N, &grp->P ) >= 0 )        \
-        MPI_CHK( mpi_sub_mpi( &N, &N, &grp->P ) )
+        MPI_CHK( mpi_sub_abs( &N, &N, &grp->P ) )
 
 /*
  * Normalize jacobian coordinates so that Z == 0 || Z == 1  (GECC 3.2.1)
@@ -1117,7 +1030,7 @@
 }
 
 /*
- * Addition or subtraction: R = P + Q or R = P + Q,
+ * Addition or subtraction: R = P + Q or R = P - Q,
  * mixed affine-Jacobian coordinates (GECC 3.22)
  *
  * The coordinates of Q must be normalized (= affine),
@@ -1667,6 +1580,409 @@
     return( ecp_mul( grp, Q, d, &grp->G, f_rng, p_rng ) );
 }
 
+#if defined(POLARSSL_ECP_NIST_OPTIM)
+/*
+ * Fast reduction modulo the primes used by the NIST curves.
+ *
+ * These functions are: critical for speed, but not need for correct
+ * operations. So, we make the choice to heavily rely on the internals of our
+ * bignum library, which creates a tight coupling between these functions and
+ * our MPI implementation.  However, the coupling between the ECP module and
+ * MPI remains loose, since these functions can be deactivated at will.
+ */
+
+#if defined(POLARSSL_ECP_DP_SECP192R1_ENABLED)
+/*
+ * Compared to the way things are presented in FIPS 186-3 D.2,
+ * we proceed in columns, from right (least significant chunk) to left,
+ * adding chunks to N in place, and keeping a carry for the next chunk.
+ * This avoids moving things around in memory, and uselessly adding zeros,
+ * compared to the more straightforward, line-oriented approach.
+ *
+ * For this prime we need to handle data in chunks of 64 bits.
+ * Since this is always a multiple of our basic t_uint, we can
+ * use a t_uint * to designate such a chunk, and small loops to handle it.
+ */
+
+/* Add 64-bit chunks (dst += src) and update carry */
+static inline void add64( t_uint *dst, t_uint *src, t_uint *carry )
+{
+    unsigned char i;
+    t_uint c = 0;
+    for( i = 0; i < 8 / sizeof( t_uint ); i++, dst++, src++ )
+    {
+        *dst += c;      c  = ( *dst < c );
+        *dst += *src;   c += ( *dst < *src );
+    }
+    *carry += c;
+}
+
+/* Add carry to a 64-bit chunk and update carry */
+static inline void carry64( t_uint *dst, t_uint *carry )
+{
+    unsigned char i;
+    for( i = 0; i < 8 / sizeof( t_uint ); i++, dst++ )
+    {
+        *dst += *carry;
+        *carry  = ( *dst < *carry );
+    }
+}
+
+#define WIDTH       8 / sizeof( t_uint )
+#define A( i )      N->p + i * WIDTH
+#define ADD( i )    add64( p, A( i ), &c )
+#define NEXT        p += WIDTH; carry64( p, &c )
+#define LAST        p += WIDTH; *p = c; while( ++p < end ) *p = 0
+
+/*
+ * Fast quasi-reduction modulo p192 (FIPS 186-3 D.2.1)
+ */
+static int ecp_mod_p192( mpi *N )
+{
+    int ret;
+    t_uint c = 0;
+    t_uint *p, *end;
+
+    /* Make sure we have enough blocks so that A(5) is legal */
+    MPI_CHK( mpi_grow( N, 6 * WIDTH ) );
+
+    p = N->p;
+    end = p + N->n;
+
+    ADD( 3 ); ADD( 5 );             NEXT; // A0 += A3 + A5
+    ADD( 3 ); ADD( 4 ); ADD( 5 );   NEXT; // A1 += A3 + A4 + A5
+    ADD( 4 ); ADD( 5 );             LAST; // A2 += A4 + A5
+
+cleanup:
+    return( ret );
+}
+
+#undef WIDTH
+#undef A
+#undef ADD
+#undef NEXT
+#undef LAST
+#endif /* POLARSSL_ECP_DP_SECP192R1_ENABLED */
+
+#if defined(POLARSSL_ECP_DP_SECP224R1_ENABLED) ||   \
+    defined(POLARSSL_ECP_DP_SECP256R1_ENABLED) ||   \
+    defined(POLARSSL_ECP_DP_SECP384R1_ENABLED)
+/*
+ * The reader is advised to first understand ecp_mod_p192() since the same
+ * general structure is used here, but with additional complications:
+ * (1) chunks of 32 bits, and (2) subtractions.
+ */
+
+/*
+ * For these primes, we need to handle data in chunks of 32 bits.
+ * This makes it more complicated if we use 64 bits limbs in MPI,
+ * which prevents us from using a uniform access method as for p192.
+ *
+ * So, we define a mini abstraction layer to access 32 bit chunks,
+ * load them in 'cur' for work, and store them back from 'cur' when done.
+ *
+ * While at it, also define the size of N in terms of 32-bit chunks.
+ */
+#define LOAD32      cur = A( i );
+
+#if defined(POLARSSL_HAVE_INT8)     /* 8 bit */
+
+#define MAX32       N->n / 4
+#define A( j )      (uint32_t)( N->p[4*j+0]       ) |  \
+                              ( N->p[4*j+1] << 8  ) |  \
+                              ( N->p[4*j+2] << 16 ) |  \
+                              ( N->p[4*j+3] << 24 )
+#define STORE32     N->p[4*i+0] = (uint8_t)( cur       );   \
+                    N->p[4*i+1] = (uint8_t)( cur >> 8  );   \
+                    N->p[4*i+2] = (uint8_t)( cur >> 16 );   \
+                    N->p[4*i+3] = (uint8_t)( cur >> 24 );
+
+#elif defined(POLARSSL_HAVE_INT16)  /* 16 bit */
+
+#define MAX32       N->n / 2
+#define A( j )      (uint32_t)( N->p[2*j] ) | ( N->p[2*j+1] << 16 )
+#define STORE32     N->p[2*i+0] = (uint16_t)( cur       );  \
+                    N->p[2*i+1] = (uint16_t)( cur >> 16 );
+
+#elif defined(POLARSSL_HAVE_INT32)  /* 32 bit */
+
+#define MAX32       N->n
+#define A( j )      N->p[j]
+#define STORE32     N->p[i] = cur;
+
+#else                               /* 64-bit */
+
+#define MAX32       N->n * 2
+#define A( j ) j % 2 ? (uint32_t)( N->p[j/2] >> 32 ) : (uint32_t)( N->p[j/2] )
+#define STORE32                                   \
+    if( i % 2 ) {                                 \
+        N->p[i/2] &= 0x00000000FFFFFFFF;          \
+        N->p[i/2] |= ((uint64_t) cur) << 32;      \
+    } else {                                      \
+        N->p[i/2] &= 0xFFFFFFFF00000000;          \
+        N->p[i/2] |= (uint64_t) cur;              \
+    }
+
+#endif /* sizeof( t_uint ) */
+
+/*
+ * Helpers for addition and subtraction of chunks, with signed carry.
+ */
+static inline void add32( uint32_t *dst, uint32_t src, signed char *carry )
+{
+    *dst += src;
+    *carry += ( *dst < src );
+}
+
+static inline void sub32( uint32_t *dst, uint32_t src, signed char *carry )
+{
+    *carry -= ( *dst < src );
+    *dst -= src;
+}
+
+#define ADD( j )    add32( &cur, A( j ), &c );
+#define SUB( j )    sub32( &cur, A( j ), &c );
+
+/*
+ * Helpers for the main 'loop'
+ * (see fix_negative for the motivation of C)
+ */
+#define INIT( b )                                           \
+    int ret;                                                \
+    signed char c = 0, cc;                                  \
+    uint32_t cur;                                           \
+    size_t i = 0, bits = b;                                 \
+    mpi C;                                                  \
+    t_uint Cp[ b / 8 / sizeof( t_uint) + 1 ];               \
+                                                            \
+    C.s = 1;                                                \
+    C.n = b / 8 / sizeof( t_uint) + 1;                      \
+    C.p = Cp;                                               \
+    memset( Cp, 0, C.n * sizeof( t_uint ) );                \
+                                                            \
+    MPI_CHK( mpi_grow( N, b * 2 / 8 / sizeof( t_uint ) ) ); \
+    LOAD32;
+
+#define NEXT                    \
+    STORE32; i++; LOAD32;       \
+    cc = c; c = 0;              \
+    if( cc < 0 )                \
+        sub32( &cur, -cc, &c ); \
+    else                        \
+        add32( &cur, cc, &c );  \
+
+#define LAST                                    \
+    STORE32; i++;                               \
+    cur = c > 0 ? c : 0; STORE32;               \
+    cur = 0; while( ++i < MAX32 ) { STORE32; }  \
+    if( c < 0 ) fix_negative( N, c, &C, bits );
+
+/*
+ * If the result is negative, we get it in the form
+ * c * 2^(bits + 32) + N, with c negative and N positive shorter than 'bits'
+ */
+static inline int fix_negative( mpi *N, signed char c, mpi *C, size_t bits )
+{
+    int ret;
+
+    /* C = - c * 2^(bits + 32) */
+#if !defined(POLARSSL_HAVE_INT64)
+    ((void) bits);
+#else
+    if( bits == 224 )
+        C->p[ C->n - 1 ] = ((t_uint) -c) << 32;
+    else
+#endif
+        C->p[ C->n - 1 ] = (t_uint) -c;
+
+    /* N = - ( C - N ) */
+    MPI_CHK( mpi_sub_abs( N, C, N ) );
+    N->s = -1;
+
+cleanup:
+
+    return( ret );
+}
+
+#if defined(POLARSSL_ECP_DP_SECP224R1_ENABLED)
+/*
+ * Fast quasi-reduction modulo p224 (FIPS 186-3 D.2.2)
+ */
+static int ecp_mod_p224( mpi *N )
+{
+    INIT( 224 );
+
+    SUB(  7 ); SUB( 11 );               NEXT; // A0 += -A7 - A11
+    SUB(  8 ); SUB( 12 );               NEXT; // A1 += -A8 - A12
+    SUB(  9 ); SUB( 13 );               NEXT; // A2 += -A9 - A13
+    SUB( 10 ); ADD(  7 ); ADD( 11 );    NEXT; // A3 += -A10 + A7 + A11
+    SUB( 11 ); ADD(  8 ); ADD( 12 );    NEXT; // A4 += -A11 + A8 + A12
+    SUB( 12 ); ADD(  9 ); ADD( 13 );    NEXT; // A5 += -A12 + A9 + A13
+    SUB( 13 ); ADD( 10 );               LAST; // A6 += -A13 + A10
+
+cleanup:
+    return( ret );
+}
+#endif /* POLARSSL_ECP_DP_SECP224R1_ENABLED */
+
+#if defined(POLARSSL_ECP_DP_SECP256R1_ENABLED)
+/*
+ * Fast quasi-reduction modulo p256 (FIPS 186-3 D.2.3)
+ */
+static int ecp_mod_p256( mpi *N )
+{
+    INIT( 256 );
+
+    ADD(  8 ); ADD(  9 );
+    SUB( 11 ); SUB( 12 ); SUB( 13 ); SUB( 14 );             NEXT; // A0
+
+    ADD(  9 ); ADD( 10 );
+    SUB( 12 ); SUB( 13 ); SUB( 14 ); SUB( 15 );             NEXT; // A1
+
+    ADD( 10 ); ADD( 11 );
+    SUB( 13 ); SUB( 14 ); SUB( 15 );                        NEXT; // A2
+
+    ADD( 11 ); ADD( 11 ); ADD( 12 ); ADD( 12 ); ADD( 13 );
+    SUB( 15 ); SUB(  8 ); SUB(  9 );                        NEXT; // A3
+
+    ADD( 12 ); ADD( 12 ); ADD( 13 ); ADD( 13 ); ADD( 14 );
+    SUB(  9 ); SUB( 10 );                                   NEXT; // A4
+
+    ADD( 13 ); ADD( 13 ); ADD( 14 ); ADD( 14 ); ADD( 15 );
+    SUB( 10 ); SUB( 11 );                                   NEXT; // A5
+
+    ADD( 14 ); ADD( 14 ); ADD( 15 ); ADD( 15 ); ADD( 14 ); ADD( 13 );
+    SUB(  8 ); SUB(  9 );                                   NEXT; // A6
+
+    ADD( 15 ); ADD( 15 ); ADD( 15 ); ADD( 8 );
+    SUB( 10 ); SUB( 11 ); SUB( 12 ); SUB( 13 );             LAST; // A7
+
+cleanup:
+    return( ret );
+}
+#endif /* POLARSSL_ECP_DP_SECP256R1_ENABLED */
+
+#if defined(POLARSSL_ECP_DP_SECP384R1_ENABLED)
+/*
+ * Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)
+ */
+static int ecp_mod_p384( mpi *N )
+{
+    INIT( 384 );
+
+    ADD( 12 ); ADD( 21 ); ADD( 20 );
+    SUB( 23 );                                              NEXT; // A0
+
+    ADD( 13 ); ADD( 22 ); ADD( 23 );
+    SUB( 12 ); SUB( 20 );                                   NEXT; // A2
+
+    ADD( 14 ); ADD( 23 );
+    SUB( 13 ); SUB( 21 );                                   NEXT; // A2
+
+    ADD( 15 ); ADD( 12 ); ADD( 20 ); ADD( 21 );
+    SUB( 14 ); SUB( 22 ); SUB( 23 );                        NEXT; // A3
+
+    ADD( 21 ); ADD( 21 ); ADD( 16 ); ADD( 13 ); ADD( 12 ); ADD( 20 ); ADD( 22 );
+    SUB( 15 ); SUB( 23 ); SUB( 23 );                        NEXT; // A4
+
+    ADD( 22 ); ADD( 22 ); ADD( 17 ); ADD( 14 ); ADD( 13 ); ADD( 21 ); ADD( 23 );
+    SUB( 16 );                                              NEXT; // A5
+
+    ADD( 23 ); ADD( 23 ); ADD( 18 ); ADD( 15 ); ADD( 14 ); ADD( 22 );
+    SUB( 17 );                                              NEXT; // A6
+
+    ADD( 19 ); ADD( 16 ); ADD( 15 ); ADD( 23 );
+    SUB( 18 );                                              NEXT; // A7
+
+    ADD( 20 ); ADD( 17 ); ADD( 16 );
+    SUB( 19 );                                              NEXT; // A8
+
+    ADD( 21 ); ADD( 18 ); ADD( 17 );
+    SUB( 20 );                                              NEXT; // A9
+
+    ADD( 22 ); ADD( 19 ); ADD( 18 );
+    SUB( 21 );                                              NEXT; // A10
+
+    ADD( 23 ); ADD( 20 ); ADD( 19 );
+    SUB( 22 );                                              LAST; // A11
+
+cleanup:
+    return( ret );
+}
+#endif /* POLARSSL_ECP_DP_SECP384R1_ENABLED */
+
+#undef A
+#undef LOAD32
+#undef STORE32
+#undef MAX32
+#undef INIT
+#undef NEXT
+#undef LAST
+
+#endif /* POLARSSL_ECP_DP_SECP224R1_ENABLED ||
+          POLARSSL_ECP_DP_SECP256R1_ENABLED ||
+          POLARSSL_ECP_DP_SECP384R1_ENABLED */
+
+#if defined(POLARSSL_ECP_DP_SECP521R1_ENABLED)
+/*
+ * Here we have an actual Mersenne prime, so things are more straightforward.
+ * However, chunks are aligned on a 'weird' boundary (521 bits).
+ */
+
+/* Size of p521 in terms of t_uint */
+#define P521_WIDTH      ( 521 / 8 / sizeof( t_uint ) + 1 )
+
+/* Bits to keep in the most significant t_uint */
+#if defined(POLARSSL_HAVE_INT8)
+#define P521_MASK       0x01
+#else
+#define P521_MASK       0x01FF
+#endif
+
+/*
+ * Fast quasi-reduction modulo p521 (FIPS 186-3 D.2.5)
+ * Write N as A1 + 2^521 A0, return A0 + A1
+ */
+static int ecp_mod_p521( mpi *N )
+{
+    int ret;
+    size_t i;
+    mpi M;
+    t_uint Mp[P521_WIDTH + 1];
+    /* Worst case for the size of M is when t_uint is 16 bits:
+     * we need to hold bits 513 to 1056, which is 34 limbs, that is
+     * P521_WIDTH + 1. Otherwise P521_WIDTH is enough. */
+
+    if( N->n < P521_WIDTH )
+        return( 0 );
+
+    /* M = A1 */
+    M.s = 1;
+    M.n = N->n - ( P521_WIDTH - 1 );
+    if( M.n > P521_WIDTH + 1 )
+        M.n = P521_WIDTH + 1;
+    M.p = Mp;
+    memcpy( Mp, N->p + P521_WIDTH - 1, M.n * sizeof( t_uint ) );
+    MPI_CHK( mpi_shift_r( &M, 521 % ( 8 * sizeof( t_uint ) ) ) );
+
+    /* N = A0 */
+    N->p[P521_WIDTH - 1] &= P521_MASK;
+    for( i = P521_WIDTH; i < N->n; i++ )
+        N->p[i] = 0;
+
+    /* N = A0 + A1 */
+    MPI_CHK( mpi_add_abs( N, N, &M ) );
+
+cleanup:
+    return( ret );
+}
+
+#undef P521_WIDTH
+#undef P521_MASK
+#endif /* POLARSSL_ECP_DP_SECP521R1_ENABLED */
+
+#endif /* POLARSSL_ECP_NIST_OPTIM */
+
 #if defined(POLARSSL_SELF_TEST)
 
 /*
diff --git a/library/oid.c b/library/oid.c
index c9cfe48..a4f2c0c 100644
--- a/library/oid.c
+++ b/library/oid.c
@@ -47,9 +47,22 @@
  * Macro to generate an internal function for oid_XXX_from_asn1() (used by
  * the other functions)
  */
-#define FN_OID_TYPED_FROM_ASN1( TYPE_T, NAME, LIST )                              \
-static const TYPE_T * oid_ ## NAME ## _from_asn1( const asn1_buf *oid )           \
-{ return (const TYPE_T *) oid_descriptor_from_buf(LIST, sizeof(TYPE_T), oid->p, oid->len ); }
+#define FN_OID_TYPED_FROM_ASN1( TYPE_T, NAME, LIST )                        \
+static const TYPE_T * oid_ ## NAME ## _from_asn1( const asn1_buf *oid )     \
+{                                                                           \
+    const TYPE_T *p = LIST;                                                 \
+    const oid_descriptor_t *cur = (const oid_descriptor_t *) p;             \
+    if( p == NULL || oid == NULL ) return( NULL );                          \
+    while( cur->asn1 != NULL ) {                                            \
+        if( cur->asn1_len == oid->len &&                                    \
+            memcmp( cur->asn1, oid->p, oid->len ) == 0 ) {                  \
+            return( p );                                                    \
+        }                                                                   \
+        p++;                                                                \
+        cur = (const oid_descriptor_t *) p;                                 \
+    }                                                                       \
+    return( NULL );                                                         \
+}
 
 /*
  * Macro to generate a function for retrieving a single attribute from the
@@ -133,34 +146,6 @@
 }
 
 /*
- * Core generic function
- */
-static const oid_descriptor_t *oid_descriptor_from_buf( const void *struct_set,
-                size_t struct_size, const unsigned char *oid, size_t len )
-{
-    const unsigned char *p = (const unsigned char *) struct_set;
-    const oid_descriptor_t *cur;
-
-    if( struct_set == NULL || oid == NULL )
-        return( NULL );
-
-    cur = (const oid_descriptor_t *) p;
-    while( cur->asn1 != NULL )
-    {
-        if( cur->asn1_len == len &&
-            memcmp( cur->asn1, oid, len ) == 0 )
-        {
-            return( cur );
-        }
-
-        p += struct_size;
-        cur = (const oid_descriptor_t *) p;
-    }
-
-    return( NULL );
-}
-
-/*
  * For X520 attribute types
  */
 typedef struct {
diff --git a/library/ssl_ciphersuites.c b/library/ssl_ciphersuites.c
index a72c843..1c9f809 100644
--- a/library/ssl_ciphersuites.c
+++ b/library/ssl_ciphersuites.c
@@ -1395,4 +1395,19 @@
     }
 }
 
+int ssl_ciphersuite_uses_psk( const ssl_ciphersuite_t *info )
+{
+    switch( info->key_exchange )
+    {
+        case POLARSSL_KEY_EXCHANGE_PSK:
+        case POLARSSL_KEY_EXCHANGE_RSA_PSK:
+        case POLARSSL_KEY_EXCHANGE_DHE_PSK:
+        case POLARSSL_KEY_EXCHANGE_ECDHE_PSK:
+            return( 1 );
+
+        default:
+            return( 0 );
+    }
+}
+
 #endif
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 5b35b94..7d81fc9 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -74,8 +74,6 @@
     left -= sizeof( ssl_session );
 
 #if defined(POLARSSL_X509_CRT_PARSE_C)
-    ((ssl_session *) buf)->peer_cert = NULL;
-
     if( session->peer_cert == NULL )
         cert_len = 0;
     else
@@ -1270,6 +1268,7 @@
 
         case TLS_EXT_SUPPORTED_POINT_FORMATS:
             SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) );
+            ssl->handshake->cli_exts |= TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
 
             ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );
             if( ret != 0 )
@@ -1395,6 +1394,16 @@
                     continue;
 #endif
 
+#if defined(POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED)
+                /* If the ciphersuite requires a pre-shared key and we don't
+                 * have one, skip it now rather than failing later */
+                if( ssl_ciphersuite_uses_psk( ciphersuite_info ) &&
+                    ssl->f_psk == NULL &&
+                    ( ssl->psk == NULL || ssl->psk_identity == NULL ||
+                      ssl->psk_identity_len == 0 || ssl->psk_len == 0 ) )
+                    continue;
+#endif
+
 #if defined(POLARSSL_X509_CRT_PARSE_C)
                 /*
                  * Final check: if ciphersuite requires us to have a
@@ -1546,7 +1555,12 @@
     unsigned char *p = buf;
     ((void) ssl);
 
-    *olen = 0;
+    if( ( ssl->handshake->cli_exts &
+          TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )
+    {
+        *olen = 0;
+        return;
+    }
 
     SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) );
 
diff --git a/library/x509write_crt.c b/library/x509write_crt.c
index c3db3c4..86b4034 100644
--- a/library/x509write_crt.c
+++ b/library/x509write_crt.c
@@ -156,6 +156,7 @@
                                         0, buf + sizeof(buf) - len, len );
 }
 
+#if defined(POLARSSL_SHA1_C)
 int x509write_crt_set_subject_key_identifier( x509write_cert *ctx )
 {
     int ret;
@@ -202,6 +203,7 @@
                                    OID_SIZE( OID_AUTHORITY_KEY_IDENTIFIER ),
                                    0, buf + sizeof(buf) - len, len );
 }
+#endif /* POLARSSL_SHA1_C */
 
 int x509write_crt_set_key_usage( x509write_cert *ctx, unsigned char key_usage )
 {
diff --git a/programs/pkey/ecdsa.c b/programs/pkey/ecdsa.c
index add74c6..948066a 100644
--- a/programs/pkey/ecdsa.c
+++ b/programs/pkey/ecdsa.c
@@ -33,9 +33,14 @@
 #include <stdio.h>
 
 /*
- * Uncomment to force use of a specific curve
-#define ECPARAMS    POLARSSL_ECP_DP_SECP256R1
+ * Uncomment to show key and signature details
  */
+#define VERBOSE
+
+/*
+ * Uncomment to force use of a specific curve
+ */
+#define ECPARAMS    POLARSSL_ECP_DP_SECP192R1
 
 #if !defined(ECPARAMS)
 #define ECPARAMS    ecp_curve_list()->grp_id
@@ -53,6 +58,38 @@
     return( 0 );
 }
 #else
+
+#if defined(VERBOSE)
+static void dump_buf( char *title, unsigned char *buf, size_t len )
+{
+    size_t i;
+
+    printf( "%s", title );
+    for( i = 0; i < len; i++ )
+        printf("%c%c", "0123456789ABCDEF" [buf[i] / 16],
+                       "0123456789ABCDEF" [buf[i] % 16] );
+    printf( "\n" );
+}
+
+static void dump_pubkey( char *title, ecdsa_context *key )
+{
+    unsigned char buf[300];
+    size_t len;
+
+    if( ecp_point_write_binary( &key->grp, &key->Q,
+                POLARSSL_ECP_PF_UNCOMPRESSED, &len, buf, sizeof buf ) != 0 )
+    {
+        printf("internal error\n");
+        return;
+    }
+
+    dump_buf( title, buf, len );
+}
+#else
+#define dump_buf( a, b, c )
+#define dump_pubkey( a, b )
+#endif
+
 int main( int argc, char *argv[] )
 {
     int ret;
@@ -109,6 +146,8 @@
 
     printf( " ok (key size: %d bits)\n", (int) ctx_sign.grp.pbits );
 
+    dump_pubkey( "  + Public key: ", &ctx_sign );
+
     /*
      * Sign some message hash
      */
@@ -125,6 +164,9 @@
     }
     printf( " ok (signature length = %zu)\n", sig_len );
 
+    dump_buf( "  + Hash: ", hash, sizeof hash );
+    dump_buf( "  + Signature: ", sig, sig_len );
+
     /*
      * Signature is serialized as defined by RFC 4492 p. 20,
      * but one can also access 'r' and 's' directly from the context
diff --git a/programs/x509/cert_write.c b/programs/x509/cert_write.c
index 94dfa1d..8e4951e 100644
--- a/programs/x509/cert_write.c
+++ b/programs/x509/cert_write.c
@@ -571,6 +571,7 @@
 
     printf( " ok\n" );
 
+#if defined(POLARSSL_SHA1_C)
     printf( "  . Adding the Subject Key Identifier ..." );
     fflush( stdout );
 
@@ -596,6 +597,7 @@
     }
 
     printf( " ok\n" );
+#endif /* POLARSSL_SHA1_C */
 
     if( opt.key_usage )
     {
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 9a50a2c..2795e60 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -69,6 +69,7 @@
 add_test_suite(pbkdf2)
 add_test_suite(pkcs1_v21)
 add_test_suite(pkcs5)
+add_test_suite(pk)
 add_test_suite(pkparse)
 add_test_suite(pkwrite)
 add_test_suite(shax)
diff --git a/tests/Makefile b/tests/Makefile
index 23455a6..e266b15 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -48,6 +48,7 @@
 		test_suite_mpi			test_suite_pbkdf2		\
 		test_suite_pkcs1_v21	test_suite_pkcs5		\
 		test_suite_pkparse		test_suite_pkwrite		\
+		test_suite_pk									\
 		test_suite_rsa			test_suite_shax			\
 		test_suite_x509parse	test_suite_x509write	\
 		test_suite_xtea			test_suite_version
diff --git a/tests/scripts/generate_code.pl b/tests/scripts/generate_code.pl
index 1e33ac6..6c2ac6e 100755
--- a/tests/scripts/generate_code.pl
+++ b/tests/scripts/generate_code.pl
@@ -144,7 +144,12 @@
         my @res = $test_data =~ /^$mapping_regex/msg;
         foreach my $value (@res)
         {
-            $mapping_values{$value} = 1 if ($value !~ /^\d+$/);
+            next unless ($value !~ /^\d+$/);
+            if ( $mapping_values{$value} ) {
+                ${ $mapping_values{$value} }{$function_pre_code} = 1;
+            } else {
+                $mapping_values{$value} = { $function_pre_code => 1 };
+            }
         }
     }
 
@@ -204,13 +209,23 @@
 # Make mapping code
 while( my ($key, $value) = each(%mapping_values) )
 {
-    $mapping_code .= << "END";
+    my $key_mapping_code = << "END";
     if( strcmp( str, "$key" ) == 0 )
     {
         *value = ( $key );
         return( 0 );
     }
 END
+
+    # handle depenencies, unless used at least one without depends
+    if ($value->{""}) {
+        $mapping_code .= $key_mapping_code;
+        next;
+    }
+    for my $ifdef ( keys %$value ) {
+        (my $endif = $ifdef) =~ s!ifdef!endif //!g;
+        $mapping_code .= $ifdef . $key_mapping_code . $endif;
+    }
 }
 
 $dispatch_code =~ s/^(.+)/    $1/mg;
diff --git a/tests/suites/helpers.function b/tests/suites/helpers.function
index 881a0ac..b334954 100644
--- a/tests/suites/helpers.function
+++ b/tests/suites/helpers.function
@@ -2,6 +2,14 @@
 #include "polarssl/memory.h"
 #endif
 
+#if defined(WANT_NOT_RND_MPI)
+#if defined(POLARSSL_BIGNUM_C)
+#include "polarssl/bignum.h"
+#else
+#error "not_rnd_mpi() need bignum.c"
+#endif
+#endif
+
 #ifdef _MSC_VER
 #include <basetsd.h>
 typedef UINT32 uint32_t;
@@ -225,48 +233,36 @@
     return( 0 );
 }
 
+#if defined(WANT_NOT_RND_MPI)
 /**
- * This function returns a buffer given as a hex string.
+ * NOT random function, to match test vectors.
  *
- * The buffer is reversed so that the following are equivalent:
- *   mpi_fill_random( x, len, not_rnd, str );
+ * The following are equivalent:
+ *   mpi_fill_random( x, strlen( str ) / 2, not_rnd, str );
  *   mpi_read_string( x, 16, str );
- * (So, not random at all. Usefull to match test vectors.)
- * Based on unhexify(), just reversed (changes marked by "sic")
+ * Warning: no other use is supported!
  */
-static int not_rnd( void *in, unsigned char *out, size_t len )
+#define ciL    (sizeof(t_uint))         /* chars in limb  */
+#define CHARS_TO_LIMBS(i) (((i) + ciL - 1) / ciL)
+static int not_rnd_mpi( void *in, unsigned char *out, size_t len )
 {
-    unsigned char *obuf;
-    const char *ibuf = in;
-    unsigned char c, c2;
-    assert( len == strlen(ibuf) / 2 );
-    assert(!(strlen(ibuf) %1)); // must be even number of bytes
+    char *str = (char *) in;
+    mpi X;
 
-    obuf = out + (len - 1); // sic
-    while (*ibuf != 0)
-    {
-        c = *ibuf++;
-        if( c >= '0' && c <= '9' )
-            c -= '0';
-        else if( c >= 'a' && c <= 'f' )
-            c -= 'a' - 10;
-        else if( c >= 'A' && c <= 'F' )
-            c -= 'A' - 10;
-        else
-            assert( 0 );
+    /*
+     * The 'in' pointer we get is from an MPI prepared by mpi_fill_random(),
+     * just reconstruct the rest in order to be able to call mpi_read_string()
+     */
+    X.s = 1;
+    X.p = (t_uint *) out;
+    X.n = CHARS_TO_LIMBS( len );
 
-        c2 = *ibuf++;
-        if( c2 >= '0' && c2 <= '9' )
-            c2 -= '0';
-        else if( c2 >= 'a' && c2 <= 'f' )
-            c2 -= 'a' - 10;
-        else if( c2 >= 'A' && c2 <= 'F' )
-            c2 -= 'A' - 10;
-        else
-            assert( 0 );
+    /*
+     * If str is too long, mpi_read_string() will try to allocate a new buffer
+     * for X.p, which we want to avoid at all costs.
+     */
+    assert( strlen( str ) / 2 == len );
 
-        *obuf-- = ( c << 4 ) | c2; // sic
-    }
-
-    return( 0 );
+    return( mpi_read_string( &X, 16, str ) );
 }
+#endif /* WANT_NOT_RND_MPI */
diff --git a/tests/suites/test_suite_ecdh.function b/tests/suites/test_suite_ecdh.function
index ba35c76..63917d7 100644
--- a/tests/suites/test_suite_ecdh.function
+++ b/tests/suites/test_suite_ecdh.function
@@ -1,5 +1,6 @@
 /* BEGIN_HEADER */
 #include <polarssl/ecdh.h>
+#define WANT_NOT_RND_MPI
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -57,14 +58,14 @@
 
     TEST_ASSERT( ecp_use_known_dp( &grp, id ) == 0 );
 
-    TEST_ASSERT( ecdh_gen_public( &grp, &dA, &qA, &not_rnd, dA_str ) == 0 );
+    TEST_ASSERT( ecdh_gen_public( &grp, &dA, &qA, &not_rnd_mpi, dA_str ) == 0 );
     TEST_ASSERT( ! ecp_is_zero( &qA ) );
     TEST_ASSERT( mpi_read_string( &check, 16, xA_str ) == 0 );
     TEST_ASSERT( mpi_cmp_mpi( &qA.X, &check ) == 0 );
     TEST_ASSERT( mpi_read_string( &check, 16, yA_str ) == 0 );
     TEST_ASSERT( mpi_cmp_mpi( &qA.Y, &check ) == 0 );
 
-    TEST_ASSERT( ecdh_gen_public( &grp, &dB, &qB, &not_rnd, dB_str ) == 0 );
+    TEST_ASSERT( ecdh_gen_public( &grp, &dB, &qB, &not_rnd_mpi, dB_str ) == 0 );
     TEST_ASSERT( ! ecp_is_zero( &qB ) );
     TEST_ASSERT( mpi_read_string( &check, 16, xB_str ) == 0 );
     TEST_ASSERT( mpi_cmp_mpi( &qB.X, &check ) == 0 );
diff --git a/tests/suites/test_suite_ecdsa.function b/tests/suites/test_suite_ecdsa.function
index 5ccb39d..34307ca 100644
--- a/tests/suites/test_suite_ecdsa.function
+++ b/tests/suites/test_suite_ecdsa.function
@@ -1,5 +1,6 @@
 /* BEGIN_HEADER */
 #include <polarssl/ecdsa.h>
+#define WANT_NOT_RND_MPI
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -63,7 +64,7 @@
     len = unhexify(buf, hash_str);
 
     TEST_ASSERT( ecdsa_sign( &grp, &r, &s, &d, buf, len,
-                &not_rnd, k_str ) == 0 );
+                &not_rnd_mpi, k_str ) == 0 );
 
     TEST_ASSERT( mpi_cmp_mpi( &r, &r_check ) == 0 );
     TEST_ASSERT( mpi_cmp_mpi( &s, &s_check ) == 0 );
diff --git a/tests/suites/test_suite_ecp.data b/tests/suites/test_suite_ecp.data
index 9eb302b..2f5f4ef 100644
--- a/tests/suites/test_suite_ecp.data
+++ b/tests/suites/test_suite_ecp.data
@@ -253,14 +253,58 @@
 depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
 ecp_gen_keypair:POLARSSL_ECP_DP_SECP192R1
 
+ECP mod p192 small (more than 192 bits, less limbs than 2 * 192 bits)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"0100000000000103010000000000010201000000000001010100000000000100"
+
 ECP mod p192 readable
 depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
-ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"000000000000010500000000000001040000000000000103000000000000010200000000000001010000000000000100"
+ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"010000000000010501000000000001040100000000000103010000000000010201000000000001010100000000000100"
+
+ECP mod p192 readable with carry
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"FF00000000010500FF00000000010400FF00000000010300FF00000000010200FF00000000010100FF00000000010000"
 
 ECP mod p192 random
 depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
 ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"36CF96B45D706A0954D89E52CE5F38517A2270E0175849B6F3740151D238CCABEF921437E475881D83BB69E4AA258EBD"
 
+ECP mod p192 (from a past failure case)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP192R1:"1AC2D6F96A2A425E9DD1776DD8368D4BBC86BF4964E79FEA713583BF948BBEFF0939F96FB19EC48C585BDA6A2D35C750"
+
+ECP mod p224 readable without carry
+depends_on:POLARSSL_ECP_DP_SECP224R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP224R1:"0000000D0000000C0000000B0000000A0000000900000008000000070000FF060000FF050000FF040000FF03000FF0020000FF010000FF00"
+
+ECP mod p224 readable with negative carry
+depends_on:POLARSSL_ECP_DP_SECP224R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP224R1:"0000000D0000000C0000000B0000000A00000009000000080000000700000006000000050000000400000003000000020000000100000000"
+
+ECP mod p224 readable with positive carry
+depends_on:POLARSSL_ECP_DP_SECP224R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP224R1:"0000000D0000000C0000000BFFFFFF0AFFFFFF09FFFFFF08FFFFFF070000FF060000FF050000FF040000FF03000FF0020000FF010000FF00"
+
+ECP mod p224 readable with final negative carry
+depends_on:POLARSSL_ECP_DP_SECP224R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP224R1:"FF00000D0000000C0000000B0000000A00000009000000080000000700000006000000050000000400000003000000020000000100000000"
+
+ECP mod p521 very small
+depends_on:POLARSSL_ECP_DP_SECP521R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP521R1:"01"
+
+ECP mod p521 small (522 bits)
+depends_on:POLARSSL_ECP_DP_SECP521R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP521R1:"030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+
+ECP mod p521 readable
+depends_on:POLARSSL_ECP_DP_SECP521R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP521R1:"03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+
+ECP mod p521 readable with carry
+depends_on:POLARSSL_ECP_DP_SECP521R1_ENABLED
+ecp_fast_mod:POLARSSL_ECP_DP_SECP521R1:"03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"
+
 ECP test vectors secp192r1 rfc 5114
 depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
 ecp_test_vect:POLARSSL_ECP_DP_SECP192R1:"323FA3169D8E9C6593F59476BC142000AB5BE0E249C43426":"CD46489ECFD6C105E7B3D32566E2B122E249ABAADD870612":"68887B4877DF51DD4DC3D6FD11F0A26F8FD3844317916E9A":"631F95BB4A67632C9C476EEE9AB695AB240A0499307FCF62":"519A121680E0045466BA21DF2EEE47F5973B500577EF13D5":"FF613AB4D64CEE3A20875BDB10F953F6B30CA072C60AA57F":"AD420182633F8526BFE954ACDA376F05E5FF4F837F54FEBE":"4371545ED772A59741D0EDA32C671112B7FDDD51461FCF32"
diff --git a/tests/suites/test_suite_ecp.function b/tests/suites/test_suite_ecp.function
index 6981f47..4eb5259 100644
--- a/tests/suites/test_suite_ecp.function
+++ b/tests/suites/test_suite_ecp.function
@@ -229,8 +229,9 @@
     mpi_init( &N ); mpi_init( &R );
     ecp_group_init( &grp );
 
-    TEST_ASSERT( ecp_use_known_dp( &grp, id ) == 0 );
     TEST_ASSERT( mpi_read_string( &N, 16, N_str ) == 0 );
+    TEST_ASSERT( ecp_use_known_dp( &grp, id ) == 0 );
+    TEST_ASSERT( grp.modp != NULL );
 
     /*
      * Store correct result before we touch N
diff --git a/tests/suites/test_suite_error.function b/tests/suites/test_suite_error.function
index 4129f3d..a514cee 100644
--- a/tests/suites/test_suite_error.function
+++ b/tests/suites/test_suite_error.function
@@ -12,7 +12,7 @@
 {
     char buf[500];
 
-    error_strerror( code, buf, 500 );
+    polarssl_strerror( code, buf, 500 );
 
     TEST_ASSERT( strcmp( buf, result_str ) == 0 );
 }
diff --git a/tests/suites/test_suite_pk.data b/tests/suites/test_suite_pk.data
new file mode 100644
index 0000000..e4f3d95
--- /dev/null
+++ b/tests/suites/test_suite_pk.data
@@ -0,0 +1,79 @@
+PK utils: RSA
+depends_on:POLARSSL_RSA_C
+pk_utils:POLARSSL_PK_RSA:512:64:"RSA"
+
+PK utils: ECKEY
+depends_on:POLARSSL_ECP_C
+pk_utils:POLARSSL_PK_ECKEY:192:24:"EC"
+
+PK utils: ECKEY_DH
+depends_on:POLARSSL_ECP_C
+pk_utils:POLARSSL_PK_ECKEY_DH:192:24:"EC_DH"
+
+PK utils: ECDSA
+depends_on:POLARSSL_ECDSA_C
+pk_utils:POLARSSL_PK_ECDSA:192:24:"ECDSA"
+
+RSA verify test vector #1 (good)
+depends_on:POLARSSL_SHA1_C:POLARSSL_PKCS1_V15
+pk_rsa_verify_test_vec:"206ef4bf396c6087f8229ef196fd35f37ccb8de5efcdb238f20d556668f114257a11fbe038464a67830378e62ae9791453953dac1dbd7921837ba98e84e856eb80ed9487e656d0b20c28c8ba5e35db1abbed83ed1c7720a97701f709e3547a4bfcabca9c89c57ad15c3996577a0ae36d7c7b699035242f37954646c1cd5c08ac":POLARSSL_MD_SHA1:1024:16:"e28a13548525e5f36dccb24ecb7cc332cc689dfd64012604c9c7816d72a16c3f5fcdc0e86e7c03280b1c69b586ce0cd8aec722cc73a5d3b730310bf7dfebdc77ce5d94bbc369dc18a2f7b07bd505ab0f82224aef09fdc1e5063234255e0b3c40a52e9e8ae60898eb88a766bdd788fe9493d8fd86bcdd2884d5c06216c65469e5":16:"3":"5abc01f5de25b70867ff0c24e222c61f53c88daf42586fddcd56f3c4588f074be3c328056c063388688b6385a8167957c6e5355a510e005b8a851d69c96b36ec6036644078210e5d7d326f96365ee0648882921492bc7b753eb9c26cdbab37555f210df2ca6fec1b25b463d38b81c0dcea202022b04af5da58aa03d77be949b7":0
+
+RSA verify test vector #2 (bad)
+depends_on:POLARSSL_SHA1_C:POLARSSL_PKCS1_V15
+pk_rsa_verify_test_vec:"d6248c3e96b1a7e5fea978870fcc4c9786b4e5156e16b7faef4557d667f730b8bc4c784ef00c624df5309513c3a5de8ca94c2152e0459618666d3148092562ebc256ffca45b27fd2d63c68bd5e0a0aefbe496e9e63838a361b1db6fc272464f191490bf9c029643c49d2d9cd08833b8a70b4b3431f56fb1eb55ccd39e77a9c92":POLARSSL_MD_SHA1:1024:16:"e28a13548525e5f36dccb24ecb7cc332cc689dfd64012604c9c7816d72a16c3f5fcdc0e86e7c03280b1c69b586ce0cd8aec722cc73a5d3b730310bf7dfebdc77ce5d94bbc369dc18a2f7b07bd505ab0f82224aef09fdc1e5063234255e0b3c40a52e9e8ae60898eb88a766bdd788fe9493d8fd86bcdd2884d5c06216c65469e5":16:"3":"3203b7647fb7e345aa457681e5131777f1adc371f2fba8534928c4e52ef6206a856425d6269352ecbf64db2f6ad82397768cafdd8cd272e512d617ad67992226da6bc291c31404c17fd4b7e2beb20eff284a44f4d7af47fd6629e2c95809fa7f2241a04f70ac70d3271bb13258af1ed5c5988c95df7fa26603515791075feccd":POLARSSL_ERR_RSA_VERIFY_FAILED
+
+ECDSA verify test vector #1 (good)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_ec_test_vec:POLARSSL_PK_ECDSA:POLARSSL_ECP_DP_SECP192R1:"046FDD3028FA94A863CD4F78DBFF8B3AA561FC6D9CCBBCA88E0AE6FA437F5415F957542D0717FF8B84562DAE99872EF841":"546869732073686F756C64206265207468652068617368206F662061206D6573736167652E00":"30350218185B2A7FB5CD9C9A8488B119B68B47D6EC833509CE9FA1FF021900FB7D259A744A2348BD45D241A39DC915B81CC2084100FA24":0
+
+ECDSA verify test vector #2 (bad)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_ec_test_vec:POLARSSL_PK_ECDSA:POLARSSL_ECP_DP_SECP192R1:"046FDD3028FA94A863CD4F78DBFF8B3AA561FC6D9CCBBCA88E0AE6FA437F5415F957542D0717FF8B84562DAE99872EF841":"546869732073686F756C64206265207468652068617368206F662061206D6573736167652E00":"30350218185B2A7FB5CD9C9A8488B119B68B47D6EC833509CE9FA1FF021900FB7D259A744A2348BD45D241A39DC915B81CC2084100FA25":POLARSSL_ERR_ECP_VERIFY_FAILED
+
+EC(DSA) verify test vector #1 (good)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_ec_test_vec:POLARSSL_PK_ECKEY:POLARSSL_ECP_DP_SECP192R1:"046FDD3028FA94A863CD4F78DBFF8B3AA561FC6D9CCBBCA88E0AE6FA437F5415F957542D0717FF8B84562DAE99872EF841":"546869732073686F756C64206265207468652068617368206F662061206D6573736167652E00":"30350218185B2A7FB5CD9C9A8488B119B68B47D6EC833509CE9FA1FF021900FB7D259A744A2348BD45D241A39DC915B81CC2084100FA24":0
+
+EC(DSA) verify test vector #2 (bad)
+depends_on:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_ec_test_vec:POLARSSL_PK_ECKEY:POLARSSL_ECP_DP_SECP192R1:"046FDD3028FA94A863CD4F78DBFF8B3AA561FC6D9CCBBCA88E0AE6FA437F5415F957542D0717FF8B84562DAE99872EF841":"546869732073686F756C64206265207468652068617368206F662061206D6573736167652E00":"30350218185B2A7FB5CD9C9A8488B119B68B47D6EC833509CE9FA1FF021900FB7D259A744A2348BD45D241A39DC915B81CC2084100FA25":POLARSSL_ERR_ECP_VERIFY_FAILED
+
+ECDSA sign-verify
+depends_on:POLARSSL_ECDSA_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_sign_verify:POLARSSL_PK_ECDSA:0:0
+
+EC(DSA) sign-verify
+depends_on:POLARSSL_ECDSA_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_sign_verify:POLARSSL_PK_ECKEY:0:0
+
+EC_DH (no) sign-verify
+depends_on:POLARSSL_ECP_C:POLARSSL_ECP_DP_SECP192R1_ENABLED
+pk_sign_verify:POLARSSL_PK_ECKEY_DH:POLARSSL_ERR_PK_TYPE_MISMATCH:POLARSSL_ERR_PK_TYPE_MISMATCH
+
+RSA sign-verify
+depends_on:POLARSSL_RSA_C:POLARSSL_PKCS1_V15
+pk_sign_verify:POLARSSL_PK_RSA:0:0
+
+RSA encrypt test vector
+depends_on:POLARSSL_PKCS1_V15
+pk_rsa_encrypt_test_vec:"4E636AF98E40F3ADCFCCB698F4E80B9F":2048:16:"b38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034f":16:"3":"b0c0b193ba4a5b4502bfacd1a9c2697da5510f3e3ab7274cf404418afd2c62c89b98d83bbc21c8c1bf1afe6d8bf40425e053e9c03e03a3be0edbe1eda073fade1cc286cc0305a493d98fe795634c3cad7feb513edb742d66d910c87d07f6b0055c3488bb262b5fd1ce8747af64801fb39d2d3a3e57086ffe55ab8d0a2ca86975629a0f85767a4990c532a7c2dab1647997ebb234d0b28a0008bfebfc905e7ba5b30b60566a5e0190417465efdbf549934b8f0c5c9f36b7c5b6373a47ae553ced0608a161b1b70dfa509375cf7a3598223a6d7b7a1d1a06ac74d345a9bb7c0e44c8388858a4f1d8115f2bd769ffa69020385fa286302c80e950f9e2751308666c":0
+
+RSA decrypt test vector #1
+depends_on:POLARSSL_PKCS1_V15
+pk_rsa_decrypt_test_vec:"a42eda41e56235e666e7faaa77100197f657288a1bf183e4820f0c37ce2c456b960278d6003e0bbcd4be4a969f8e8fd9231e1f492414f00ed09844994c86ec32db7cde3bec7f0c3dbf6ae55baeb2712fa609f5fc3207a824eb3dace31849cd6a6084318523912bccb84cf42e3c6d6d1685131d69bb545acec827d2b0dfdd5568b7dcc4f5a11d6916583fefa689d367f8c9e1d95dcd2240895a9470b0c1730f97cd6e8546860bd254801769f54be96e16362ddcbf34d56035028890199e0f48db38642cb66a4181e028a6443a404fea284ce02b4614b683367d40874e505611d23142d49f06feea831d52d347b13610b413c4efc43a6de9f0b08d2a951dc503b6":2048:16:"e79a373182bfaa722eb035f772ad2a9464bd842de59432c18bbab3a7dfeae318c9b915ee487861ab665a40bd6cda560152578e8579016c929df99fea05b4d64efca1d543850bc8164b40d71ed7f3fa4105df0fb9b9ad2a18ce182c8a4f4f975bea9aa0b9a1438a27a28e97ac8330ef37383414d1bd64607d6979ac050424fd17":16:"c6749cbb0db8c5a177672d4728a8b22392b2fc4d3b8361d5c0d5055a1b4e46d821f757c24eef2a51c561941b93b3ace7340074c058c9bb48e7e7414f42c41da4cccb5c2ba91deb30c586b7fb18af12a52995592ad139d3be429add6547e044becedaf31fa3b39421e24ee034fbf367d11f6b8f88ee483d163b431e1654ad3e89":16:"b38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034f":16:"3":"4E636AF98E40F3ADCFCCB698F4E80B9F":0
+
+RSA decrypt test vector #2
+depends_on:POLARSSL_PKCS1_V15
+pk_rsa_decrypt_test_vec:"a42eda41e56235e666e7faaa77100197f657288a1bf183e4820f0c37ce2c456b960278d6003e0bbcd4be4a969f8e8fd9231e1f492414f00ed09844994c86ec32db7cde3bec7f0c3dbf6ae55baeb2712fa609f5fc3207a824eb3dace31849cd6a6084318523912bccb84cf42e3c6d6d1685131d69bb545acec827d2b0dfdd5568b7dcc4f5a11d6916583fefa689d367f8c9e1d95dcd2240895a9470b0c1730f97cd6e8546860bd254801769f54be96e16362ddcbf34d56035028890199e0f48db38642cb66a4181e028a6443a404feb284ce02b4614b683367d40874e505611d23142d49f06feea831d52d347b13610b413c4efc43a6de9f0b08d2a951dc503b6":2048:16:"e79a373182bfaa722eb035f772ad2a9464bd842de59432c18bbab3a7dfeae318c9b915ee487861ab665a40bd6cda560152578e8579016c929df99fea05b4d64efca1d543850bc8164b40d71ed7f3fa4105df0fb9b9ad2a18ce182c8a4f4f975bea9aa0b9a1438a27a28e97ac8330ef37383414d1bd64607d6979ac050424fd17":16:"c6749cbb0db8c5a177672d4728a8b22392b2fc4d3b8361d5c0d5055a1b4e46d821f757c24eef2a51c561941b93b3ace7340074c058c9bb48e7e7414f42c41da4cccb5c2ba91deb30c586b7fb18af12a52995592ad139d3be429add6547e044becedaf31fa3b39421e24ee034fbf367d11f6b8f88ee483d163b431e1654ad3e89":16:"b38ac65c8141f7f5c96e14470e851936a67bf94cc6821a39ac12c05f7c0b06d9e6ddba2224703b02e25f31452f9c4a8417b62675fdc6df46b94813bc7b9769a892c482b830bfe0ad42e46668ace68903617faf6681f4babf1cc8e4b0420d3c7f61dc45434c6b54e2c3ee0fc07908509d79c9826e673bf8363255adb0add2401039a7bcd1b4ecf0fbe6ec8369d2da486eec59559dd1d54c9b24190965eafbdab203b35255765261cd0909acf93c3b8b8428cbb448de4715d1b813d0c94829c229543d391ce0adab5351f97a3810c1f73d7b1458b97daed4209c50e16d064d2d5bfda8c23893d755222793146d0a78c3d64f35549141486c3b0961a7b4c1a2034f":16:"3":"4E636AF98E40F3ADCFCCB698F4E80B9F":POLARSSL_ERR_RSA_INVALID_PADDING
+
+EC nocrypt
+depends_on:POLARSSL_ECP_C
+pk_ec_nocrypt:POLARSSL_PK_ECKEY
+
+EC-DH nocrypt
+depends_on:POLARSSL_ECP_C
+pk_ec_nocrypt:POLARSSL_PK_ECKEY_DH
+
+ECDSA nocrypt
+depends_on:POLARSSL_ECDSA_C
+pk_ec_nocrypt:POLARSSL_PK_ECDSA
diff --git a/tests/suites/test_suite_pk.function b/tests/suites/test_suite_pk.function
new file mode 100644
index 0000000..e3db119
--- /dev/null
+++ b/tests/suites/test_suite_pk.function
@@ -0,0 +1,282 @@
+/* BEGIN_HEADER */
+#include <polarssl/pk.h>
+
+static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len );
+
+static int pk_genkey( pk_context *pk )
+{
+#if defined(POLARSSL_RSA_C)
+    if( pk_get_type( pk ) == POLARSSL_PK_RSA )
+        return rsa_gen_key( pk_rsa( *pk ), rnd_std_rand, NULL, 512, 3 );
+#endif
+#if defined(POLARSSL_ECP_C)
+    if( pk_get_type( pk ) == POLARSSL_PK_ECKEY ||
+        pk_get_type( pk ) == POLARSSL_PK_ECKEY_DH ||
+        pk_get_type( pk ) == POLARSSL_PK_ECDSA )
+    {
+        int ret;
+        if( ( ret = ecp_use_known_dp( &pk_ec( *pk )->grp,
+                                      POLARSSL_ECP_DP_SECP192R1 ) ) != 0 )
+            return( ret );
+
+        return ecp_gen_keypair( &pk_ec( *pk )->grp, &pk_ec( *pk )->d,
+                                &pk_ec( *pk )->Q, rnd_std_rand, NULL );
+    }
+#endif
+    return( -1 );
+}
+/* END_HEADER */
+
+/* BEGIN_DEPENDENCIES
+ * depends_on:POLARSSL_PK_C
+ * END_DEPENDENCIES
+ */
+
+/* BEGIN_CASE */
+void pk_utils( int type, int size, int len, char *name )
+{
+    pk_context pk;
+
+    pk_init( &pk );
+
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( type ) ) == 0 );
+    TEST_ASSERT( pk_genkey( &pk ) == 0 );
+
+    TEST_ASSERT( (int) pk_get_type( &pk ) == type );
+    TEST_ASSERT( pk_can_do( &pk, type ) );
+    TEST_ASSERT( pk_get_size( &pk ) == (unsigned) size );
+    TEST_ASSERT( pk_get_len( &pk ) == (unsigned) len );
+    TEST_ASSERT( strcmp( pk_get_name( &pk), name ) == 0 );
+
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_RSA_C */
+void pk_rsa_verify_test_vec( char *message_hex_string, int digest,
+                       int mod, int radix_N, char *input_N, int radix_E,
+                       char *input_E, char *result_hex_str, int result )
+{
+    unsigned char message_str[1000];
+    unsigned char hash_result[1000];
+    unsigned char result_str[1000];
+    rsa_context *rsa;
+    pk_context pk;
+    int msg_len;
+
+    pk_init( &pk );
+
+    memset( message_str, 0x00, 1000 );
+    memset( hash_result, 0x00, 1000 );
+    memset( result_str, 0x00, 1000 );
+
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( POLARSSL_PK_RSA ) ) == 0 );
+    rsa = pk_rsa( pk );
+
+    rsa->len = mod / 8;
+    TEST_ASSERT( mpi_read_string( &rsa->N, radix_N, input_N ) == 0 );
+    TEST_ASSERT( mpi_read_string( &rsa->E, radix_E, input_E ) == 0 );
+
+    msg_len = unhexify( message_str, message_hex_string );
+    unhexify( result_str, result_hex_str );
+
+    if( md_info_from_type( digest ) != NULL )
+        TEST_ASSERT( md( md_info_from_type( digest ), message_str, msg_len, hash_result ) == 0 );
+
+    TEST_ASSERT( pk_verify( &pk, digest, hash_result, 0,
+                            result_str, pk_get_len( &pk ) ) == result );
+
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_ECDSA_C */
+void pk_ec_test_vec( int type, int id, char *key_str,
+                     char *hash_str, char * sig_str, int ret )
+{
+    pk_context pk;
+    ecp_keypair *eckey;
+    unsigned char hash[100], sig[500], key[500];
+    size_t hash_len, sig_len, key_len;
+
+    pk_init( &pk );
+
+    memset( hash, 0, sizeof( hash ) );  hash_len = unhexify(hash, hash_str);
+    memset( sig, 0, sizeof( sig ) );    sig_len = unhexify(sig, sig_str);
+    memset( key, 0, sizeof( key ) );    key_len = unhexify(key, key_str);
+
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( type ) ) == 0 );
+
+    TEST_ASSERT( pk_can_do( &pk, POLARSSL_PK_ECDSA ) );
+    eckey = pk_ec( pk );
+
+    TEST_ASSERT( ecp_use_known_dp( &eckey->grp, id ) == 0 );
+    TEST_ASSERT( ecp_point_read_binary( &eckey->grp, &eckey->Q,
+                                        key, key_len ) == 0 );
+
+    TEST_ASSERT( pk_verify( &pk, POLARSSL_MD_NONE,
+                            hash, hash_len, sig, sig_len ) == ret );
+
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void pk_sign_verify( int type, int sign_ret, int verify_ret )
+{
+    pk_context pk;
+    unsigned char hash[50], sig[5000];
+    size_t sig_len;
+
+    pk_init( &pk );
+
+    memset( hash, 0x2a, sizeof hash );
+    memset( sig, 0, sizeof sig );
+
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( type ) ) == 0 );
+    TEST_ASSERT( pk_genkey( &pk ) == 0 );
+
+    TEST_ASSERT( pk_sign( &pk, POLARSSL_MD_NONE, hash, sizeof hash,
+                          sig, &sig_len, rnd_std_rand, NULL ) == sign_ret );
+
+    TEST_ASSERT( pk_verify( &pk, POLARSSL_MD_NONE,
+                            hash, sizeof hash, sig, sig_len ) == verify_ret );
+
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_RSA_C */
+void pk_rsa_encrypt_test_vec( char *message_hex, int mod,
+                            int radix_N, char *input_N,
+                            int radix_E, char *input_E,
+                            char *result_hex, int ret )
+{
+    unsigned char message[1000];
+    unsigned char output[1000];
+    unsigned char result[1000];
+    size_t msg_len, olen, res_len;
+    rnd_pseudo_info rnd_info;
+    rsa_context *rsa;
+    pk_context pk;
+
+    memset( &rnd_info,  0, sizeof( rnd_pseudo_info ) );
+    memset( message,    0, sizeof( message ) );
+    memset( output,     0, sizeof( output ) );
+    memset( result,     0, sizeof( result ) );
+
+    msg_len = unhexify( message, message_hex );
+    res_len = unhexify( result, result_hex );
+
+    pk_init( &pk );
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( POLARSSL_PK_RSA ) ) == 0 );
+    rsa = pk_rsa( pk );
+
+    rsa->len = mod / 8;
+    TEST_ASSERT( mpi_read_string( &rsa->N, radix_N, input_N ) == 0 );
+    TEST_ASSERT( mpi_read_string( &rsa->E, radix_E, input_E ) == 0 );
+
+    TEST_ASSERT( pk_encrypt( &pk, message, msg_len,
+                             output, &olen, sizeof( output ),
+                             rnd_pseudo_rand, &rnd_info ) == ret );
+    TEST_ASSERT( olen == res_len );
+    TEST_ASSERT( memcmp( output, result, olen ) == 0 );
+
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE depends_on:POLARSSL_RSA_C */
+void pk_rsa_decrypt_test_vec( char *cipher_hex, int mod,
+                            int radix_P, char *input_P,
+                            int radix_Q, char *input_Q,
+                            int radix_N, char *input_N,
+                            int radix_E, char *input_E,
+                            char *clear_hex, int ret )
+{
+    unsigned char clear[1000];
+    unsigned char output[1000];
+    unsigned char cipher[1000];
+    size_t clear_len, olen, cipher_len;
+    rnd_pseudo_info rnd_info;
+    mpi P1, Q1, H, G;
+    rsa_context *rsa;
+    pk_context pk;
+
+    pk_init( &pk );
+    mpi_init( &P1 ); mpi_init( &Q1 ); mpi_init( &H ); mpi_init( &G );
+
+    memset( &rnd_info,  0, sizeof( rnd_pseudo_info ) );
+    memset( clear,      0, sizeof( clear ) );
+    memset( cipher,     0, sizeof( cipher ) );
+
+    clear_len = unhexify( clear, clear_hex );
+    cipher_len = unhexify( cipher, cipher_hex );
+
+    /* init pk-rsa context */
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( POLARSSL_PK_RSA ) ) == 0 );
+    rsa = pk_rsa( pk );
+
+    /* load public key */
+    rsa->len = mod / 8;
+    TEST_ASSERT( mpi_read_string( &rsa->N, radix_N, input_N ) == 0 );
+    TEST_ASSERT( mpi_read_string( &rsa->E, radix_E, input_E ) == 0 );
+
+    /* load private key */
+    TEST_ASSERT( mpi_read_string( &rsa->P, radix_P, input_P ) == 0 );
+    TEST_ASSERT( mpi_read_string( &rsa->Q, radix_Q, input_Q ) == 0 );
+    TEST_ASSERT( mpi_sub_int( &P1, &rsa->P, 1 ) == 0 );
+    TEST_ASSERT( mpi_sub_int( &Q1, &rsa->Q, 1 ) == 0 );
+    TEST_ASSERT( mpi_mul_mpi( &H, &P1, &Q1 ) == 0 );
+    TEST_ASSERT( mpi_gcd( &G, &rsa->E, &H  ) == 0 );
+    TEST_ASSERT( mpi_inv_mod( &rsa->D , &rsa->E, &H  ) == 0 );
+    TEST_ASSERT( mpi_mod_mpi( &rsa->DP, &rsa->D, &P1 ) == 0 );
+    TEST_ASSERT( mpi_mod_mpi( &rsa->DQ, &rsa->D, &Q1 ) == 0 );
+    TEST_ASSERT( mpi_inv_mod( &rsa->QP, &rsa->Q, &rsa->P ) == 0 );
+
+    /* decryption test */
+    memset( output, 0, sizeof( output ) );
+    olen = 0;
+    TEST_ASSERT( pk_decrypt( &pk, cipher, cipher_len,
+                             output, &olen, sizeof( output ),
+                             rnd_pseudo_rand, &rnd_info ) == ret );
+    if( ret == 0 )
+    {
+        TEST_ASSERT( olen == clear_len );
+        TEST_ASSERT( memcmp( output, clear, olen ) == 0 );
+    }
+
+    mpi_free( &P1 ); mpi_free( &Q1 ); mpi_free( &H ); mpi_free( &G );
+    pk_free( &pk );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void pk_ec_nocrypt( int type )
+{
+    pk_context pk;
+    unsigned char output[100];
+    unsigned char input[100];
+    rnd_pseudo_info rnd_info;
+    size_t olen = 0;
+    int ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
+
+    pk_init( &pk );
+
+    memset( &rnd_info,  0, sizeof( rnd_pseudo_info ) );
+    memset( output,     0, sizeof( output ) );
+    memset( input,      0, sizeof( input ) );
+
+    TEST_ASSERT( pk_init_ctx( &pk, pk_info_from_type( type ) ) == 0 );
+
+    TEST_ASSERT( pk_encrypt( &pk, input, sizeof( input ),
+                             output, &olen, sizeof( output ),
+                             rnd_pseudo_rand, &rnd_info ) == ret );
+
+    TEST_ASSERT( pk_decrypt( &pk, input, sizeof( input ),
+                             output, &olen, sizeof( output ),
+                             rnd_pseudo_rand, &rnd_info ) == ret );
+
+    pk_free( &pk );
+}
+/* END_CASE */
diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function
index 32336178..8b57f8c 100644
--- a/tests/suites/test_suite_x509write.function
+++ b/tests/suites/test_suite_x509write.function
@@ -53,7 +53,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:POLARSSL_PEM_WRITE_C:POLARSSL_X509_CRT_WRITE_C */
+/* BEGIN_CASE depends_on:POLARSSL_PEM_WRITE_C:POLARSSL_X509_CRT_WRITE_C:POLARSSL_SHA1_C */
 void x509_crt_check( char *subject_key_file, char *subject_pwd,
                      char *subject_name, char *issuer_key_file,
                      char *issuer_pwd, char *issuer_name,