Merge opaque-keys-interfaces into develop

diff --git a/include/mbedtls/ecdsa.h b/include/mbedtls/ecdsa.h
index aa23d67..8725cee 100644
--- a/include/mbedtls/ecdsa.h
+++ b/include/mbedtls/ecdsa.h
@@ -51,10 +51,41 @@
 #if MBEDTLS_ECP_MAX_BYTES > 124
 #error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN"
 #endif
-/** The maximal size of an ECDSA signature in Bytes. */
-#define MBEDTLS_ECDSA_MAX_LEN  ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )
 
 /**
+ * \brief           Maximum ECDSA signature size for a given curve bit size
+ *
+ * \param bits      Curve size in bits
+ * \return          Maximum signature size in bytes
+ *
+ * \note            This macro returns a compile-time constant if its argument
+ *                  is one. It may evaluate its argument multiple times; if
+ *                  this is a problem, call the function
+ *                  mbedtls_ecdsa_max_sig_len instead.
+ */
+#define MBEDTLS_ECDSA_MAX_SIG_LEN( bits )                               \
+    ( /*T,L of SEQUENCE*/ ( ( bits ) >= 61 * 8 ? 3 : 2 ) +              \
+      /*T,L of r,s*/        2 * ( ( ( bits ) >= 127 * 8 ? 3 : 2 ) +     \
+      /*V of r,s*/                ( ( bits ) + 8 ) / 8 ) )
+
+/**
+ * \brief           Maximum ECDSA signature size for a given curve bit size
+ *
+ * \param bits      Curve size in bits
+ * \return          Maximum signature size in bytes
+ *
+ * \note            If you need a compile-time constant, call the macro
+ *                  MBEDTLS_ECDSA_MAX_SIG_LEN instead.
+ */
+static inline size_t mbedtls_ecdsa_max_sig_len( size_t bits )
+{
+    return( MBEDTLS_ECDSA_MAX_SIG_LEN( bits ) );
+}
+
+/** The maximal size of an ECDSA signature in Bytes. */
+#define MBEDTLS_ECDSA_MAX_LEN (MBEDTLS_ECDSA_MAX_SIG_LEN( \
+        8 * MBEDTLS_ECP_MAX_BYTES ) )
+/**
  * \brief           The ECDSA context structure.
  */
 typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
@@ -256,6 +287,33 @@
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 /**
+ * \brief           Convert a signature from numbers to ASN.1
+ *
+ * \param r         First number of the signature
+ * \param s         Second number of the signature
+ * \param sig       Buffer that will hold the signature
+ * \param slen      Length of the signature written
+ * \param ssize     Size of the sig buffer
+ *
+ * \note            The size of the buffer \c ssize should be at least
+ *                  `MBEDTLS_ECDSA_MAX_SIG_LEN(grp->pbits)` bytes long if
+ *                  the signature was produced from curve \c grp,
+ *                  otherwise this function will return an error.
+ *                  The output ASN.1 SEQUENCE format is as follows:
+ *                  Ecdsa-Sig-Value ::= SEQUENCE {
+ *                              r       INTEGER,
+ *                              s       INTEGER
+ *                          }
+ *
+ * \return          0 if successful,
+ *                  or a MBEDTLS_ERR_MPI_XXX or MBEDTLS_ERR_ASN1_XXX error code
+ *
+ */
+int mbedtls_ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
+                             unsigned char *sig, size_t *slen,
+                             size_t ssize );
+
+/**
  * \brief           This function reads and verifies an ECDSA signature.
  *
  * \param ctx       The ECDSA context.
diff --git a/include/mbedtls/ecp.h b/include/mbedtls/ecp.h
index b00ba4d..c6e3edb 100644
--- a/include/mbedtls/ecp.h
+++ b/include/mbedtls/ecp.h
@@ -503,6 +503,58 @@
 int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,
                          unsigned char *buf, size_t blen );
 
+#if defined(MBEDTLS_ASN1_WRITE_C) && defined(MBEDTLS_OID_C)
+/**
+ * \brief           Maximum size of the output of mbedtls_ecp_ansi_write_group
+ *
+ * \note            The maximum size of the OID of a supported group + 2 for
+ *                  tag and length. Maximum size 30 is based on the length of
+ *                  the OID for primeCurves 10-38 over GF(p) defined by the
+ *                  CDC Group, as they seem to have the longest OID out of
+ *                  curves in use.
+ */
+#define MBEDTLS_ECP_GRP_OID_MAX_SIZE ( 30 + 2 )
+
+/**
+ * \brief           Write the ANSI X9.62/RFC5480 OID ECParameters of a group
+ *
+ *                  The output is the group's OID wrapped as ASN.1.
+ *
+ * \param grp       ECP group used
+ * \param buf       Buffer to write to
+ * \param size      Buffer size
+ * \param olen      Number of bytes written to \c buf
+ * \return          0 on success
+ *                  or \c MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL
+ *                  or \c MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_ecp_ansi_write_group( const mbedtls_ecp_group *grp,
+                                  unsigned char *p, size_t size,
+                                  size_t *olen );
+
+/**
+ * \brief           Export a point in ANSI X9.62/RFC5480 ECPoint
+ *
+ *                  The output is the point wrapped as an ASN.1 octet string
+ *                  as defined in X9.62 and RFC 5480.
+ *
+ * \param ec        ECP public key or key pair
+ * \param format    Point format, should be a MBEDTLS_ECP_PF_XXX macro
+ * \param p         Buffer to write to
+ * \param size      Buffer size
+ * \param olen      Number of bytes written to \c buf
+ *
+ * \return          0 on success
+ *                  or \c MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL
+ *                  or \c MBEDTLS_ERR_ECP_BAD_INPUT_DATA
+ *                  or \c MBEDTLS_ERR_ASN1_BUF_TOO_SMALL
+ */
+int mbedtls_ecp_ansi_write_point( const mbedtls_ecp_keypair *ec,
+                                  int format,
+                                  unsigned char *p,
+                                  size_t size, size_t *olen );
+#endif /* defined(MBEDTLS_ASN1_WRITE_C) && defined(MBEDTLS_OID_C) */
+
 /**
  * \brief           Multiplication by an integer: R = m * P
  *                  (Not thread-safe to use same group in multiple threads)
diff --git a/include/mbedtls/error.h b/include/mbedtls/error.h
index 8b4d3a8..5d3dcac 100644
--- a/include/mbedtls/error.h
+++ b/include/mbedtls/error.h
@@ -84,7 +84,7 @@
  * X509      2   20
  * PKCS5     2   4 (Started from top)
  * DHM       3   11
- * PK        3   15 (Started from top)
+ * PK        3   18 (Started from top)
  * RSA       4   11
  * ECP       4   9 (Started from top)
  * MD        5   5
diff --git a/include/mbedtls/oid.h b/include/mbedtls/oid.h
index bf2ef5e..239a37d 100644
--- a/include/mbedtls/oid.h
+++ b/include/mbedtls/oid.h
@@ -283,6 +283,8 @@
 
 /*
  * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2
+ * When adding new OID's, please update \c MBEDTLS_ECP_GRP_OID_MAX_SIZE
+ * in ecp.h
  */
 
 /* secp192r1 OBJECT IDENTIFIER ::= {
diff --git a/include/mbedtls/pk.h b/include/mbedtls/pk.h
index 1059bda..54b4c4a 100644
--- a/include/mbedtls/pk.h
+++ b/include/mbedtls/pk.h
@@ -1,10 +1,9 @@
 /**
  * \file pk.h
  *
- * \brief Public Key abstraction layer
- */
-/*
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief Public Key cryptography abstraction layer
+ *
+ *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -50,6 +49,9 @@
 #define inline __inline
 #endif
 
+/** \name Error codes */
+/**@{*/
+
 #define MBEDTLS_ERR_PK_ALLOC_FAILED        -0x3F80  /**< Memory allocation failed. */
 #define MBEDTLS_ERR_PK_TYPE_MISMATCH       -0x3F00  /**< Type mismatch, eg attempt to encrypt with an ECDSA key */
 #define MBEDTLS_ERR_PK_BAD_INPUT_DATA      -0x3E80  /**< Bad input parameters to function. */
@@ -65,22 +67,34 @@
 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The signature is valid but its length is less than expected. */
 #define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880  /**< PK hardware accelerator failed. */
+#define MBEDTLS_ERR_PK_INVALID_SIGNATURE   -0x3800  /**< Invalid signature */
+#define MBEDTLS_ERR_PK_BUFFER_TOO_SMALL    -0x3780  /**< Output buffer too small */
+#define MBEDTLS_ERR_PK_NOT_PERMITTED       -0x3700  /**< Operation not permitted */
+
+/**@}*/
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
+/** \name Asymmetric cryptography operation contexts */
+/**@{*/
+
 /**
- * \brief          Public key types
- */
+ * \brief           Asymmetric operation context types
+ *
+ * \note            An opaque key may be an RSA or ECC key or a key of an
+ *                  unrecognized type. Call \c mbedtls_pk_can_do() to check
+ *                  whether a key is of a recognized type. */
 typedef enum {
-    MBEDTLS_PK_NONE=0,
-    MBEDTLS_PK_RSA,
-    MBEDTLS_PK_ECKEY,
-    MBEDTLS_PK_ECKEY_DH,
-    MBEDTLS_PK_ECDSA,
-    MBEDTLS_PK_RSA_ALT,
-    MBEDTLS_PK_RSASSA_PSS,
+    MBEDTLS_PK_NONE=0,          /**< Unused context object */
+    MBEDTLS_PK_RSA,             /**< RSA key pair (normal software implementation) with PKCS#1 v1.5 or PSS context */
+    MBEDTLS_PK_ECKEY,           /**< ECC key pair with ECDSA context */
+    MBEDTLS_PK_ECKEY_DH,        /**< ECC key pair with ECDH context */
+    MBEDTLS_PK_ECDSA,           /**< ECC key pair with ECDSA context */
+    MBEDTLS_PK_RSA_ALT,         /**< RSA (alternative implementation) */
+    MBEDTLS_PK_RSASSA_PSS,      /**< RSA key pair; same context as MBEDTLS_PK_RSA, but used to represent keys with the algorithm identifier id-RSASSA-PSS */
+    MBEDTLS_PK_OPAQUE,          /**< Opaque key pair (cryptographic material held in an external module).*/
 } mbedtls_pk_type_t;
 
 /**
@@ -118,29 +132,88 @@
 #define MBEDTLS_PK_DEBUG_MAX_ITEMS 3
 
 /**
- * \brief           Public key information and operations
+ * \brief           Key pair information and operations
  */
 typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
 
 /**
- * \brief           Public key container
+ * \brief           Key pair container
  */
 typedef struct
 {
-    const mbedtls_pk_info_t *   pk_info; /**< Public key informations        */
-    void *                      pk_ctx;  /**< Underlying public key context  */
+    const mbedtls_pk_info_t *   pk_info; /**< Algorithm information          */
+    void *                      pk_ctx;  /**< Underlying key pair context */
 } mbedtls_pk_context;
 
+/**
+ * \brief           Access the type name
+ *
+ * \param ctx       Context to use
+ *
+ * \return          Type name on success, or "invalid PK"
+ */
+const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );
+
+/**
+ * \brief           Get the key type
+ *
+ * \param ctx       Context to use
+ *
+ * \return          Type on success, or MBEDTLS_PK_NONE
+ *
+ * \note            This function returns the type of the key pair object. The
+ *                  type encodes the representation of the object as well as
+ *                  the operations that it can be used for. To test whether
+ *                  the object represents a key of a recognized type such
+ *                  as RSA or ECDSA, call \c mbedtls_pk_can_do().
+ */
+mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
+
+/**
+ * \brief           Get the representation type associated with a given type
+ *
+ * \param type      Any key type
+ * \return          A canonical representative among the types with the
+ *                  same key representation. This is \c MBEDTLS_PK_RSA
+ *                  for RSA keys using the built-in software engine and
+ *                  MBEDTLS_PK_ECKEY for EC keys using the built-in
+ *                  software engine. Note that for keys of type
+ *                  \c MBEDTLS_PK_OPAQUE, the type does not specify the
+ *                  representation.
+ */
+static inline mbedtls_pk_type_t mbedtls_pk_representation_type( mbedtls_pk_type_t type )
+{
+    switch( type )
+    {
+        case MBEDTLS_PK_RSA:
+        case MBEDTLS_PK_RSASSA_PSS:
+            return( MBEDTLS_PK_RSA );
+        case MBEDTLS_PK_ECKEY:
+        case MBEDTLS_PK_ECKEY_DH:
+        case MBEDTLS_PK_ECDSA:
+            return( MBEDTLS_PK_ECKEY );
+        default:
+            return( type );
+    }
+}
+
 #if defined(MBEDTLS_RSA_C)
 /**
  * Quick access to an RSA context inside a PK context.
  *
- * \warning You must make sure the PK context actually holds an RSA context
- * before using this function!
+ * \warning You must either make sure the PK context actually holds a
+ * transparent RSA context by checking
+ * \c mbedtls_pk_representation_type( mbedtls_pk_get_type( &pk ) ) before using
+ * this function, or check that the return value is not NULL before using it.
  */
 static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk )
 {
-    return( (mbedtls_rsa_context *) (pk).pk_ctx );
+    mbedtls_pk_type_t type =
+        mbedtls_pk_representation_type( mbedtls_pk_get_type( &pk ) );
+    if( type == MBEDTLS_PK_RSA )
+        return( (mbedtls_rsa_context *)( pk.pk_ctx ) );
+    else
+        return( NULL );
 }
 #endif /* MBEDTLS_RSA_C */
 
@@ -148,12 +221,19 @@
 /**
  * Quick access to an EC context inside a PK context.
  *
- * \warning You must make sure the PK context actually holds an EC context
- * before using this function!
+ * \warning You must either make sure the PK context actually holds a
+ * transparent RSA context by checking
+ * \c mbedtls_pk_representation_type( mbedtls_pk_get_type( &pk ) ) before using
+ * this function, or check that the return value is not NULL before using it.
  */
 static inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk )
 {
-    return( (mbedtls_ecp_keypair *) (pk).pk_ctx );
+    mbedtls_pk_type_t type =
+        mbedtls_pk_representation_type( mbedtls_pk_get_type( &pk ) );
+    if( type == MBEDTLS_PK_ECKEY )
+        return( (mbedtls_ecp_keypair *)( pk.pk_ctx ) );
+    else
+        return( NULL );
 }
 #endif /* MBEDTLS_ECP_C */
 
@@ -172,10 +252,17 @@
 #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
 
 /**
- * \brief           Return information associated with the given PK type
+ * \brief           Return default information associated with the given PK type
  *
  * \param pk_type   PK type to search for.
  *
+ * \note            Different PK objects with the same type may have different
+ *                  information. This function returns the information needed
+ *                  to create a object with the default implementation
+ *                  for the given PK operation type (rsa module for an RSA
+ *                  context, ecdh module for an ECDH context, ecdsa module for
+ *                  an ECDSA context).
+ *
  * \return          The PK info associated with the type or NULL if not found.
  */
 const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
@@ -201,7 +288,17 @@
  *                  MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
  *                  MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
  *
- * \note            For contexts holding an RSA-alt key, use
+ * \note            Engines that implement opaque keys may offer an
+ *                  alternative setup function that take engine-dependent
+ *                  parameters. If such a function exists, call it
+ *                  instead of mbedtls_pk_setup. A standard way of providing
+ *                  such function is by first calling the generic
+ *                  mbedtls_pk_setup function (in particular taking care of
+ *                  context allocation through ctx_alloc) and afterwards
+ *                  proceeding to initialize the implementation-specific
+ *                  context structure.
+ *
+ * \note            For contexts holding an RSA-alt key pair, use
  *                  \c mbedtls_pk_setup_rsa_alt() instead.
  */
 int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );
@@ -211,7 +308,7 @@
  * \brief           Initialize an RSA-alt context
  *
  * \param ctx       Context to initialize. Must be empty (type NONE).
- * \param key       RSA key pointer
+ * \param key       RSA key pair pointer
  * \param decrypt_func  Decryption function
  * \param sign_func     Signing function
  * \param key_len_func  Function returning key length in bytes
@@ -240,6 +337,11 @@
  * \brief           Get the length in bytes of the underlying key
  * \param ctx       Context to use
  *
+ * \note            This returns the minimum number of bytes required to
+ *                  store the part of the key that defines its size (modulus
+ *                  for RSA, coordinate for ECC). The way the key is stored
+ *                  in the context may have a different size.
+ *
  * \return          Key length in bytes, or 0 on error
  */
 static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx )
@@ -248,13 +350,24 @@
 }
 
 /**
- * \brief           Tell if a context can do the operation given by type
+ * \brief           Tell if a context can do the operations given by type
+ *
+ * \note            This function can be used to identify the type of key
+ *                  (e.g. RSA vs ECC), and a superset of permitted
+ *                  operations. It is possible that this function returns
+ *                  true but some operations are not allowed. For example
+ *                  this function always returns true if ctx is an RSA
+ *                  context and type is MBEDTLS_PK_RSA, but the key may
+ *                  be restricted to any subset of operations among signature,
+ *                  verification, encryption and decryption. To determine
+ *                  which operations a key allow, attempt the operation and
+ *                  check the return status.
  *
  * \param ctx       Context to test
  * \param type      Target type
  *
- * \return          0 if context can't do the operations,
- *                  1 otherwise.
+ * \return          1 if context can do the operations,
+ *                  0 otherwise.
  */
 int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
 
@@ -271,7 +384,7 @@
  * \return          0 on success (signature is valid),
  *                  MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
  *                  valid but its actual length is less than sig_len,
- *                  or a specific error code.
+ *                  or a type-specific error code.
  *
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
  *                  Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... )
@@ -304,7 +417,7 @@
  *                  used for this type of signatures,
  *                  MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
  *                  valid but its actual length is less than sig_len,
- *                  or a specific error code.
+ *                  or a type-specific error code.
  *
  * \note            If hash_len is 0, then the length associated with md_alg
  *                  is used instead, or an error returned if it is invalid.
@@ -328,11 +441,18 @@
  * \param hash      Hash of the message to sign
  * \param hash_len  Hash length or 0 (see notes)
  * \param sig       Place to write the signature
- * \param sig_len   Number of bytes written
+ * \param sig_len   Actual length in bytes of the created signature
  * \param f_rng     RNG function
  * \param p_rng     RNG parameter
  *
- * \return          0 on success, or a specific error code.
+ * \return          0 on success, or a type-specific error code.
+ *
+ * \note            The signature buffer \c sig must be of appropriate size
+ *                  which can be calculated with
+ *                  \c mbedtls_pk_get_signature_size.
+ *                  Depending on the algorithm, the value returned in
+ *                  \c sig_len may be less or equal to the value returned by
+ *                  \c mbedtls_pk_get_signature_size.
  *
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
  *                  There is no interface in the PK module to make RSASSA-PSS
@@ -350,6 +470,15 @@
              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
 
 /**
+ * \brief           Calculate the size of a signature made with this key.
+ *
+ * \param ctx       PK context to use
+ *
+ * \return          Maximum size in bytes of a signature made with this key.
+ */
+size_t mbedtls_pk_get_signature_size( const mbedtls_pk_context *ctx );
+
+/**
  * \brief           Decrypt message (including padding if relevant).
  *
  * \param ctx       PK context to use - must hold a private key
@@ -363,7 +492,7 @@
  *
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
  *
- * \return          0 on success, or a specific error code.
+ * \return          0 on success, or a type-specific error code.
  */
 int mbedtls_pk_decrypt( mbedtls_pk_context *ctx,
                 const unsigned char *input, size_t ilen,
@@ -384,7 +513,7 @@
  *
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
  *
- * \return          0 on success, or a specific error code.
+ * \return          0 on success, or a type-specific error code.
  */
 int mbedtls_pk_encrypt( mbedtls_pk_context *ctx,
                 const unsigned char *input, size_t ilen,
@@ -397,7 +526,19 @@
  * \param pub       Context holding a public key.
  * \param prv       Context holding a private (and public) key.
  *
- * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
+ * \return          * 0 on success.
+ *                  * MBEDTLS_ERR_PK_BAD_INPUT_DATA if one of the contexts
+ *                    is ill-formed.
+ *                  * MBEDTLS_ERR_PK_TYPE_MISMATCH if the contexts cannot
+ *                    represent keys of the same type.
+ *                  * MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if it is impossible
+ *                    to determine whether the keys match. This can only happen
+ *                    if \c prv is an opaque key.
+ *                  * Or a type-specific error code.
+ *
+ * \note            Opaque key types may omit implementing this function
+ *                  by providing a NULL pointer in the mbedtls_pk_info_t structure.
+ *                  An opaque \c pub never matches a transparent \c prv.
  */
 int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );
 
@@ -407,27 +548,16 @@
  * \param ctx       Context to use
  * \param items     Place to write debug items
  *
- * \return          0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
+ * \return          * 0 on success.
+ *                  * MBEDTLS_ERR_PK_BAD_INPUT_DATA if the context is ill-formed.
+ *                  * MBEDTLS_ERR_PK_TYPE_MISMATCH if the context does not
+ *                    support exporting debug information.
+ *                  * Or a type-specific error code.
  */
 int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items );
 
-/**
- * \brief           Access the type name
- *
- * \param ctx       Context to use
- *
- * \return          Type name on success, or "invalid PK"
- */
-const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx );
+/**@}*/
 
-/**
- * \brief           Get the key type
- *
- * \param ctx       Context to use
- *
- * \return          Type on success, or MBEDTLS_PK_NONE
- */
-mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
 
 #if defined(MBEDTLS_PK_PARSE_C)
 /** \ingroup pk_module */
@@ -513,7 +643,12 @@
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_PK_PARSE_C */
 
+
+
 #if defined(MBEDTLS_PK_WRITE_C)
+/** \name Key pair serialization */
+/**@{*/
+
 /**
  * \brief           Write a private key to a PKCS#1 or SEC1 DER structure
  *                  Note: data is written at the end of the buffer! Use the
@@ -567,11 +702,13 @@
  */
 int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size );
 #endif /* MBEDTLS_PEM_WRITE_C */
+/**@}*/
 #endif /* MBEDTLS_PK_WRITE_C */
 
-/*
- * WARNING: Low-level functions. You probably do not want to use these unless
- *          you are certain you do ;)
+/** \name Low-level functions */
+/**@{*/
+/**
+ * \warning You probably do not want to use these unless you are certain you do ;)
  */
 
 #if defined(MBEDTLS_PK_PARSE_C)
@@ -611,6 +748,8 @@
 int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n );
 #endif
 
+/**@}*/
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/mbedtls/pk_info.h b/include/mbedtls/pk_info.h
new file mode 100644
index 0000000..a4bba46
--- /dev/null
+++ b/include/mbedtls/pk_info.h
@@ -0,0 +1,273 @@
+/**
+ * \file pk_info.h
+ *
+ * \brief Public Key cryptography abstraction layer: object interface
+ *
+ *  This file contains the info structure interface used by developers to
+ *  provide engine-specific implementations of opaque key handling functions.
+ *
+ *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+
+#ifndef MBEDTLS_PK_INFO_H
+#define MBEDTLS_PK_INFO_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include "pk.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Methods that opaque key pair objects must implement.
+ *
+ * Engines that interface with external cryptographic processors must
+ * implement this interface. It allows using different engines for each key.
+ * Platform-specific hardware accelerators that can be used for all keys of
+ * a given type should not use this interface, but rather provide an
+ * alternative implementation of the respective cryptographic module - for
+ * example to use an RSA accelerator you can define MBEDTLS_RSA_ALT, and
+ * provide your own implementation of the RSA module.
+ *
+ * \warning: If you are using the PK interface to perform operations on
+ * keys, call the functions in pk.h. The interface in this file should only
+ * be used by implementers of opaque key engines.
+ *
+ * An engine for asymmetric cryptography must implement the interface
+ * described in this structure. The interface for the engine may be
+ * exposed in one of two ways:
+ *
+ * - Declare the mbedtls_pk_info_t structure and instruct users to call
+ *   mbedtls_pk_setup with that structure.
+ * - Keep the mbedtls_pk_info_t structure hidden and declare a function
+ *   to call instead of mbedtls_pk_setup. This function should have an
+ *   interface of the form
+ *    `int mbedtls_pk_setup_myengine(mbedtls_pk_context *, ...)`
+ *   where the extra parameters depend on the engine, e.g. handles to keys
+ *   stored in an external cryptographic module.
+ *
+ * Unless otherwise indicated, functions returning int must return an
+ * Mbed TLS status code, either 0 for success or a negative value to indicate
+ * an error. It is recommended to use the MBEDTLS_ERR_PK_XXX error codes
+ * defined in pk.h.
+ *
+ * Some methods are optional; this is clearly indicated in their description.
+ * If a method is optional, then an opaque key implementation may put NULL
+ * in the corresponding field. The corresponding function in pk.h will
+ * return MBEDTLS_ERR_PK_TYPE_MISMATCH in this case.
+ *
+ *
+ * \warning: Do not declare this structure directly! It may be extended in
+ * future* versions of Mbed TLS. Call the macro
+ * MBEDTLS_PK_OPAQUE_INFO_1() instead.
+ * This macro is guaranteed to take parameters with the same type
+ * and semantics as previous versions and fill any new field of the
+ * structure with sensible values.
+ */
+struct mbedtls_pk_info_t
+{
+    /** Key pair type.
+     *
+     * mbedtls_pk_get_type() returns this value.
+     *
+     * For transparent keys, this contains an indication of supported
+     * algorithms. For opaque keys, this is \c MBEDTLS_PK_OPAQUE. */
+    mbedtls_pk_type_t type;
+
+    /** Type name.
+     *
+     * mbedtls_pk_get_name() returns this value. It must be a
+     * null-terminated string.
+     *
+     * For transparent keys, this reflects the key type. For opaque keys,
+     * this reflects the cryptographic module driver. */
+    const char *name;
+
+    /** Get key size in bits.
+     *
+     * mbedtls_pk_get_bitlen() returns this value.
+     *
+     * This function cannot fail. */
+    size_t (*get_bitlen)( const void *ctx );
+
+    /** Tell if the context implements the algorithm specified by
+     * the provided type (e.g.\ ECKEY can do ECDSA).
+     *
+     * mbedtls_pk_can_do() calls this function.
+     *
+     * This function is only based on the key type. It does not take any
+     * usage restrictions into account. */
+    int (*can_do)( const void * ctx, mbedtls_pk_type_t type );
+
+    /** Upper bound of the signature length
+     *
+     * mbedtls_pk_get_signature_size() returns this value.
+     *
+     * In case of an error, or an unsupported key type, 0 should be returned.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * signature. */
+    size_t (*signature_size_func)( const void *ctx );
+
+    /** Verify signature
+     *
+     * mbedtls_pk_verify() calls this function.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * signature verification. */
+    int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,
+                        const unsigned char *hash, size_t hash_len,
+                        const unsigned char *sig, size_t sig_len );
+
+    /** Make signature
+     *
+     * mbedtls_pk_sign() calls this function.
+     *
+     * Assume that the buffer \c sig has room for
+     * \c signature_size_func(ctx) bytes.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * signature. */
+    int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,
+                      const unsigned char *hash, size_t hash_len,
+                      unsigned char *sig, size_t *sig_len,
+                      int (*f_rng)(void *, unsigned char *, size_t),
+                      void *p_rng );
+
+    /** Decrypt message
+     *
+     * mbedtls_pk_decrypt() calls this function.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * decryption. */
+    int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
+                         unsigned char *output, size_t *olen, size_t osize,
+                         int (*f_rng)(void *, unsigned char *, size_t),
+                         void *p_rng );
+
+    /** Encrypt message
+     *
+     * mbedtls_pk_decrypt() calls this function.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * encryption. */
+    int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
+                         unsigned char *output, size_t *olen, size_t osize,
+                         int (*f_rng)(void *, unsigned char *, size_t),
+                         void *p_rng );
+
+    /** Check public-private key pair
+     *
+     * mbedtls_pk_check_pair() calls this function on the private key pair
+     * object \c prv. The other argument \c pub may be of any type, but it
+     * is guaranteed to be initialized.
+     *
+     * Opaque implementations may omit this method. */
+    int (*check_pair_func)( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );
+
+    /** Allocate a new context
+     *
+     * mbedtls_pk_setup() calls this function.
+     *
+     * If this function returns NULL, the allocation is considered to
+     * have failed and the the object remains uninitialized.
+     *
+     * Opaque implementations may omit this method. In this case,
+     * mbedtls_pk_setup will set the \c pk_ctx field of the mbedtls_pk_context
+     * object to NULL, and it is up to an engine-specific setup function to
+     * initialize the \c pk_ctx field. This is useful if the size of the
+     * memory depends on extra parameters passed to the engine-specific setup
+     * function. */
+    void * (*ctx_alloc_func)( void );
+
+    /** Free the given context
+     *
+     * mbedtls_pk_free() calls this function. It must free the data allocated
+     * by \b ctx_alloc_func as well as any other resource that belongs to
+     * the object.
+     * */
+    void (*ctx_free_func)( void *ctx );
+
+    /** Interface with the debug module
+     *
+     * mbedtls_pk_debug() calls this function.
+     *
+     * Opaque implementations may omit this method. */
+    void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );
+
+};
+
+#define MBEDTLS_PK_OPAQUE_INFO_1(               \
+    name                                        \
+    , get_bitlen                                \
+    , can_do                                    \
+    , signature_size_func                       \
+    , verify_func                               \
+    , sign_func                                 \
+    , decrypt_func                              \
+    , encrypt_func                              \
+    , check_pair_func                           \
+    , ctx_alloc_func                            \
+    , ctx_free_func                             \
+    , debug_func                                \
+    )                                           \
+    {                                           \
+        MBEDTLS_PK_OPAQUE                       \
+        , name                                  \
+        , get_bitlen                            \
+        , can_do                                \
+        , signature_size_func                   \
+        , verify_func                           \
+        , sign_func                             \
+        , decrypt_func                          \
+        , encrypt_func                          \
+        , check_pair_func                       \
+        , ctx_alloc_func                        \
+        , ctx_free_func                         \
+        , debug_func                            \
+    }
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_PK_INFO_H */
diff --git a/include/mbedtls/pk_internal.h b/include/mbedtls/pk_internal.h
index 3dae0fc..0a33087 100644
--- a/include/mbedtls/pk_internal.h
+++ b/include/mbedtls/pk_internal.h
@@ -1,10 +1,12 @@
 /**
  * \file pk_internal.h
  *
- * \brief Public Key abstraction layer: wrapper functions
- */
-/*
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief Public Key cryptography abstraction layer: built-in key types
+ *
+ *  This file contains built-in types for handling various key types using
+ *  the interface defined in pk_info.h.
+ *
+ *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -22,8 +24,8 @@
  *  This file is part of mbed TLS (https://tls.mbed.org)
  */
 
-#ifndef MBEDTLS_PK_WRAP_H
-#define MBEDTLS_PK_WRAP_H
+#ifndef MBEDTLS_PK_INTERNAL_H
+#define MBEDTLS_PK_INTERNAL_H
 
 #if !defined(MBEDTLS_CONFIG_FILE)
 #include "config.h"
@@ -33,57 +35,6 @@
 
 #include "pk.h"
 
-struct mbedtls_pk_info_t
-{
-    /** Public key type */
-    mbedtls_pk_type_t type;
-
-    /** Type name */
-    const char *name;
-
-    /** Get key size in bits */
-    size_t (*get_bitlen)( const void * );
-
-    /** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */
-    int (*can_do)( mbedtls_pk_type_t type );
-
-    /** Verify signature */
-    int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,
-                        const unsigned char *hash, size_t hash_len,
-                        const unsigned char *sig, size_t sig_len );
-
-    /** Make signature */
-    int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,
-                      const unsigned char *hash, size_t hash_len,
-                      unsigned char *sig, size_t *sig_len,
-                      int (*f_rng)(void *, unsigned char *, size_t),
-                      void *p_rng );
-
-    /** Decrypt message */
-    int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
-                         unsigned char *output, size_t *olen, size_t osize,
-                         int (*f_rng)(void *, unsigned char *, size_t),
-                         void *p_rng );
-
-    /** Encrypt message */
-    int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
-                         unsigned char *output, size_t *olen, size_t osize,
-                         int (*f_rng)(void *, unsigned char *, size_t),
-                         void *p_rng );
-
-    /** Check public-private key pair */
-    int (*check_pair_func)( const void *pub, const void *prv );
-
-    /** Allocate a new context */
-    void * (*ctx_alloc_func)( void );
-
-    /** Free the given context */
-    void (*ctx_free_func)( void *ctx );
-
-    /** Interface with the debug module */
-    void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );
-
-};
 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
 /* Container for RSA-alt */
 typedef struct
@@ -112,4 +63,4 @@
 extern const mbedtls_pk_info_t mbedtls_rsa_alt_info;
 #endif
 
-#endif /* MBEDTLS_PK_WRAP_H */
+#endif /* MBEDTLS_PK_INTERNAL_H */