Merge pull request #5608 from AndrzejKurek/raw-key-agreement-fail

Add a test for a raw key agreement failure
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aac526e..cea12f1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -52,10 +52,6 @@
 The list of maintained branches can be found in the [Current Branches section
 of BRANCHES.md](BRANCHES.md#current-branches).
 
-The only currently maintained LTS branch is:
-1. [mbedtls-2.16](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-2.16)
-
-
 Tests
 -----
 As mentioned, tests that show the correctness of the feature or bug fix should be added to the pull request, if no such tests exist.
diff --git a/ChangeLog.d/alert_reentrant.txt b/ChangeLog.d/alert_reentrant.txt
new file mode 100644
index 0000000..691d64c
--- /dev/null
+++ b/ChangeLog.d/alert_reentrant.txt
@@ -0,0 +1,5 @@
+Bugfix
+   * Fix bug in the alert sending function mbedtls_ssl_send_alert_message()
+     potentially leading to corrupted alert messages being sent in case
+     the function needs to be re-called after initially returning
+     MBEDTLS_SSL_WANT_WRITE. Fixes #1916.
diff --git a/ChangeLog.d/ccm_star_no_tag.txt b/ChangeLog.d/ccm_star_no_tag.txt
new file mode 100644
index 0000000..21e829c
--- /dev/null
+++ b/ChangeLog.d/ccm_star_no_tag.txt
@@ -0,0 +1,4 @@
+Bugfix
+   * Declare or use PSA_WANT_ALG_CCM_STAR_NO_TAG following the general
+     pattern for PSA_WANT_xxx symbols. Previously you had to specify
+     PSA_WANT_ALG_CCM for PSA_ALG_CCM_STAR_NO_TAG.
diff --git a/ChangeLog.d/fix-parllel-cmake-build-fail.txt b/ChangeLog.d/fix-parllel-cmake-build-fail.txt
new file mode 100644
index 0000000..4746c7b
--- /dev/null
+++ b/ChangeLog.d/fix-parllel-cmake-build-fail.txt
@@ -0,0 +1,3 @@
+Bugfix
+   * Fix a race condition in out-of-source builds with CMake when generated data
+     files are already present. Fixes #5374
diff --git a/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt b/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt
new file mode 100644
index 0000000..6878645
--- /dev/null
+++ b/ChangeLog.d/fix-windows-cmake-build-with-shared-libraries.txt
@@ -0,0 +1,3 @@
+Bugfix
+   * Fix compilation on Windows when building shared library, by setting
+     library search path to CMAKE_CURRENT_BINARY_DIR.
diff --git a/ChangeLog.d/mbedtls_ssl_hs_cb_t.txt b/ChangeLog.d/mbedtls_ssl_hs_cb_t.txt
new file mode 100644
index 0000000..28c3371
--- /dev/null
+++ b/ChangeLog.d/mbedtls_ssl_hs_cb_t.txt
@@ -0,0 +1,4 @@
+Features
+   * Introduce mbedtls_ssl_hs_cb_t typedef for use with
+     mbedtls_ssl_conf_cert_cb() and perhaps future callbacks
+     during TLS handshake.
diff --git a/configs/config-no-entropy.h b/configs/config-no-entropy.h
index edba4a0..31fab4e 100644
--- a/configs/config-no-entropy.h
+++ b/configs/config-no-entropy.h
@@ -21,7 +21,7 @@
  */
 /*
  * Minimal configuration of features that do not require an entropy source
- * Distinguishing reatures:
+ * Distinguishing features:
  * - no entropy module
  * - no TLS protocol implementation available due to absence of an entropy
  *   source
diff --git a/include/mbedtls/config_psa.h b/include/mbedtls/config_psa.h
index dd3554d..f917133 100644
--- a/include/mbedtls/config_psa.h
+++ b/include/mbedtls/config_psa.h
@@ -50,6 +50,12 @@
 #define PSA_WANT_ALG_ECDSA_ANY PSA_WANT_ALG_ECDSA
 #endif
 
+#if defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) && !defined(PSA_WANT_ALG_CCM)
+#define PSA_WANT_ALG_CCM PSA_WANT_ALG_CCM_STAR_NO_TAG
+#elif !defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) && defined(PSA_WANT_ALG_CCM)
+#define PSA_WANT_ALG_CCM_STAR_NO_TAG PSA_WANT_ALG_CCM
+#endif
+
 #if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
 #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW
 #elif !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
@@ -384,7 +390,8 @@
 #endif
 #endif /* PSA_WANT_ALG_XTS */
 
-#if defined(PSA_WANT_ALG_ECB_NO_PADDING)
+#if defined(PSA_WANT_ALG_ECB_NO_PADDING) &&     \
+    !defined(MBEDTLS_PSA_ACCEL_ALG_ECB_NO_PADDING)
 #define MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING 1
 #endif
 
@@ -411,6 +418,7 @@
     defined(PSA_HAVE_SOFT_KEY_TYPE_ARIA) || \
     defined(PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA)
 #define MBEDTLS_PSA_BUILTIN_ALG_CCM 1
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG 1
 #define MBEDTLS_CCM_C
 #endif
 #endif /* PSA_WANT_ALG_CCM */
@@ -545,7 +553,9 @@
 
 #if defined(MBEDTLS_CCM_C)
 #define MBEDTLS_PSA_BUILTIN_ALG_CCM 1
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG 1
 #define PSA_WANT_ALG_CCM 1
+#define PSA_WANT_ALG_CCM_STAR_NO_TAG 1
 #endif /* MBEDTLS_CCM_C */
 
 #if defined(MBEDTLS_CMAC_C)
diff --git a/include/mbedtls/mbedtls_config.h b/include/mbedtls/mbedtls_config.h
index e8a2705..72a1e10 100644
--- a/include/mbedtls/mbedtls_config.h
+++ b/include/mbedtls/mbedtls_config.h
@@ -129,7 +129,12 @@
  * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and
  * MBEDTLS_PLATFORM_STD_TIME.
  *
- * Comment if your system does not support time functions
+ * Comment if your system does not support time functions.
+ *
+ * \note If MBEDTLS_TIMING_C is set - to enable the semi-portable timing
+ *       interface - timing.c will include time.h on suitable platforms
+ *       regardless of the setting of MBEDTLS_HAVE_TIME, unless
+ *       MBEDTLS_TIMING_ALT is used. See timing.c for more information.
  */
 #define MBEDTLS_HAVE_TIME
 
@@ -1273,7 +1278,7 @@
  * Enable an implementation of SHA-256 that has lower ROM footprint but also
  * lower performance.
  *
- * The default implementation is meant to be a reasonnable compromise between
+ * The default implementation is meant to be a reasonable compromise between
  * performance and size. This version optimizes more aggressively for size at
  * the expense of performance. Eg on Cortex-M4 it reduces the size of
  * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about
@@ -3013,6 +3018,10 @@
  * your own implementation of the whole module by setting
  * \c MBEDTLS_TIMING_ALT in the current file.
  *
+ * \note The timing module will include time.h on suitable platforms
+ *       regardless of the setting of MBEDTLS_HAVE_TIME, unless
+ *       MBEDTLS_TIMING_ALT is used. See timing.c for more information.
+ *
  * \note See also our Knowledge Base article about porting to a new
  * environment:
  * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
diff --git a/include/mbedtls/pk.h b/include/mbedtls/pk.h
index 324612a..7e056db 100644
--- a/include/mbedtls/pk.h
+++ b/include/mbedtls/pk.h
@@ -330,8 +330,8 @@
  *                  storing and manipulating the key material directly.
  *
  * \param ctx       The context to initialize. It must be empty (type NONE).
- * \param key       The PSA key to wrap, which must hold an ECC key pair
- *                  (see notes below).
+ * \param key       The PSA key to wrap, which must hold an ECC or RSA key
+ *                  pair (see notes below).
  *
  * \note            The wrapped key must remain valid as long as the
  *                  wrapping PK context is in use, that is at least between
@@ -339,8 +339,8 @@
  *                  mbedtls_pk_free() is called on this context. The wrapped
  *                  key might then be independently used or destroyed.
  *
- * \note            This function is currently only available for ECC key
- *                  pairs (that is, ECC keys containing private key material).
+ * \note            This function is currently only available for ECC or RSA
+ *                  key pairs (that is, keys containing private key material).
  *                  Support for other key types may be added later.
  *
  * \return          \c 0 on success.
@@ -923,7 +923,8 @@
  *                  change or be removed at any time without notice.
  *
  * \note            Only ECDSA keys are supported so far. Signing with the
- *                  specified hash is the only allowed use of that key.
+ *                  specified hash & ECDH key agreement derivation operation
+ *                  are the only allowed use of that key.
  *
  * \param pk        Input: the EC key to import to a PSA key.
  *                  Output: a PK context wrapping that PSA key.
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index 9be083a..9b29c85 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -1218,6 +1218,25 @@
                                         const unsigned char server_random[32],
                                         mbedtls_tls_prf_types tls_prf_type );
 
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief           Callback type: generic handshake callback
+ *
+ * \note            Callbacks may use user_data funcs to set/get app user data.
+ *                  See \c mbedtls_ssl_get_user_data_p()
+ *                      \c mbedtls_ssl_get_user_data_n()
+ *                      \c mbedtls_ssl_conf_get_user_data_p()
+ *                      \c mbedtls_ssl_conf_get_user_data_n()
+ *
+ * \param ssl       \c mbedtls_ssl_context on which the callback is run
+ *
+ * \return          The return value of the callback is 0 if successful,
+ *                  or a specific MBEDTLS_ERR_XXX code, which will cause
+ *                  the handshake to be aborted.
+ */
+typedef int (*mbedtls_ssl_hs_cb_t)( mbedtls_ssl_context *ssl );
+#endif
+
 /* A type for storing user data in a library structure.
  *
  * The representation of type may change in future versions of the library.
@@ -1477,7 +1496,7 @@
     mbedtls_ssl_user_data_t MBEDTLS_PRIVATE(user_data);
 
 #if defined(MBEDTLS_SSL_SRV_C)
-    int (*MBEDTLS_PRIVATE(f_cert_cb))(mbedtls_ssl_context *); /*!< certificate selection callback */
+    mbedtls_ssl_hs_cb_t MBEDTLS_PRIVATE(f_cert_cb);  /*!< certificate selection callback */
 #endif /* MBEDTLS_SSL_SRV_C */
 };
 
@@ -2278,19 +2297,15 @@
  *                  If set, the callback is always called for each handshake,
  *                  after `ClientHello` processing has finished.
  *
- *                  The callback has the following parameters:
- *                  - \c mbedtls_ssl_context*: The SSL context to which
- *                                             the operation applies.
- *                  The return value of the callback is 0 if successful,
- *                  or a specific MBEDTLS_ERR_XXX code, which will cause
- *                  the handshake to be aborted.
- *
  * \param conf      The SSL configuration to register the callback with.
  * \param f_cert_cb The callback for selecting server certificate after
  *                  `ClientHello` processing has finished.
  */
-void mbedtls_ssl_conf_cert_cb( mbedtls_ssl_config *conf,
-                               int (*f_cert_cb)(mbedtls_ssl_context *) );
+static inline void mbedtls_ssl_conf_cert_cb( mbedtls_ssl_config *conf,
+                                             mbedtls_ssl_hs_cb_t f_cert_cb )
+{
+    conf->MBEDTLS_PRIVATE(f_cert_cb) = f_cert_cb;
+}
 #endif /* MBEDTLS_SSL_SRV_C */
 
 /**
@@ -4812,7 +4827,7 @@
 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf );
 
 /**
- * \brief          Load reasonnable default SSL configuration values.
+ * \brief          Load reasonable default SSL configuration values.
  *                 (You need to call mbedtls_ssl_config_init() first.)
  *
  * \param conf     SSL configuration context
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index df7f170..6bb2ad3 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -260,6 +260,7 @@
 endif(USE_STATIC_MBEDTLS_LIBRARY)
 
 if(USE_SHARED_MBEDTLS_LIBRARY)
+    set(CMAKE_LIBRARY_PATH ${CMAKE_CURRENT_BINARY_DIR})
     add_library(${mbedcrypto_target} SHARED ${src_crypto})
     set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 3.1.0 SOVERSION 11)
     target_link_libraries(${mbedcrypto_target} PUBLIC ${libs})
diff --git a/library/bignum.c b/library/bignum.c
index 288f859..f06eff0 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -38,6 +38,7 @@
 #if defined(MBEDTLS_BIGNUM_C)
 
 #include "mbedtls/bignum.h"
+#include "bignum_internal.h"
 #include "bn_mul.h"
 #include "mbedtls/platform_util.h"
 #include "mbedtls/error.h"
@@ -1369,92 +1370,36 @@
     return( mbedtls_mpi_sub_mpi( X, A, &B ) );
 }
 
-/** Helper for mbedtls_mpi multiplication.
- *
- * Add \p b * \p s to \p d.
- *
- * \param i             The number of limbs of \p s.
- * \param[in] s         A bignum to multiply, of size \p i.
- *                      It may overlap with \p d, but only if
- *                      \p d <= \p s.
- *                      Its leading limb must not be \c 0.
- * \param[in,out] d     The bignum to add to.
- *                      It must be sufficiently large to store the
- *                      result of the multiplication. This means
- *                      \p i + 1 limbs if \p d[\p i - 1] started as 0 and \p b
- *                      is not known a priori.
- * \param b             A scalar to multiply.
- */
-static
-#if defined(__APPLE__) && defined(__arm__)
-/*
- * Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
- * appears to need this to prevent bad ARM code generation at -O3.
- */
-__attribute__ ((noinline))
-#endif
-void mpi_mul_hlp( size_t i,
-                  const mbedtls_mpi_uint *s,
-                  mbedtls_mpi_uint *d,
-                  mbedtls_mpi_uint b )
+mbedtls_mpi_uint mbedtls_mpi_core_mla( mbedtls_mpi_uint *d, size_t d_len,
+                                       const mbedtls_mpi_uint *s, size_t s_len,
+                                       mbedtls_mpi_uint b )
 {
-    mbedtls_mpi_uint c = 0, t = 0;
+    mbedtls_mpi_uint c = 0; /* carry */
+    size_t excess_len = d_len - s_len;
 
-#if defined(MULADDC_HUIT)
-    for( ; i >= 8; i -= 8 )
+    size_t steps_x8 = s_len / 8;
+    size_t steps_x1 = s_len & 7;
+
+    while( steps_x8-- )
     {
-        MULADDC_INIT
-        MULADDC_HUIT
-        MULADDC_STOP
+        MULADDC_X8_INIT
+        MULADDC_X8_CORE
+        MULADDC_X8_STOP
     }
 
-    for( ; i > 0; i-- )
+    while( steps_x1-- )
     {
-        MULADDC_INIT
-        MULADDC_CORE
-        MULADDC_STOP
-    }
-#else /* MULADDC_HUIT */
-    for( ; i >= 16; i -= 16 )
-    {
-        MULADDC_INIT
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_STOP
+        MULADDC_X1_INIT
+        MULADDC_X1_CORE
+        MULADDC_X1_STOP
     }
 
-    for( ; i >= 8; i -= 8 )
-    {
-        MULADDC_INIT
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_CORE   MULADDC_CORE
-        MULADDC_STOP
-    }
-
-    for( ; i > 0; i-- )
-    {
-        MULADDC_INIT
-        MULADDC_CORE
-        MULADDC_STOP
-    }
-#endif /* MULADDC_HUIT */
-
-    t++;
-
-    while( c != 0 )
+    while( excess_len-- )
     {
         *d += c; c = ( *d < c ); d++;
     }
+
+    return( c );
 }
 
 /*
@@ -1490,8 +1435,14 @@
     MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, i + j ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
 
-    for( ; j > 0; j-- )
-        mpi_mul_hlp( i, A->p, X->p + j - 1, B->p[j - 1] );
+    for( size_t k = 0; k < j; k++ )
+    {
+        /* We know that there cannot be any carry-out since we're
+         * iterating from bottom to top. */
+        (void) mbedtls_mpi_core_mla( X->p + k, i + 1,
+                                     A->p, i,
+                                     B->p[k] );
+    }
 
     /* If the result is 0, we don't shortcut the operation, which reduces
      * but does not eliminate side channels leaking the zero-ness. We do
@@ -1517,19 +1468,15 @@
     MPI_VALIDATE_RET( X != NULL );
     MPI_VALIDATE_RET( A != NULL );
 
-    /* mpi_mul_hlp can't deal with a leading 0. */
     size_t n = A->n;
     while( n > 0 && A->p[n - 1] == 0 )
         --n;
 
-    /* The general method below doesn't work if n==0 or b==0. By chance
-     * calculating the result is trivial in those cases. */
+    /* The general method below doesn't work if b==0. */
     if( b == 0 || n == 0 )
-    {
         return( mbedtls_mpi_lset( X, 0 ) );
-    }
 
-    /* Calculate A*b as A + A*(b-1) to take advantage of mpi_mul_hlp */
+    /* Calculate A*b as A + A*(b-1) to take advantage of mbedtls_mpi_core_mla */
     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
     /* In general, A * b requires 1 limb more than b. If
      * A->p[n - 1] * b / b == A->p[n - 1], then A * b fits in the same
@@ -1538,10 +1485,13 @@
      * making the call to grow() unconditional causes slightly fewer
      * calls to calloc() in ECP code, presumably because it reuses the
      * same mpi for a while and this way the mpi is more likely to directly
-     * grow to its final size. */
+     * grow to its final size.
+     *
+     * Note that calculating A*b as 0 + A*b doesn't work as-is because
+     * A,X can be the same. */
     MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, n + 1 ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, A ) );
-    mpi_mul_hlp( n, A->p, X->p, b - 1 );
+    mbedtls_mpi_core_mla( X->p, X->n, A->p, n, b - 1 );
 
 cleanup:
     return( ret );
@@ -1907,8 +1857,8 @@
  * \param           mm  The value calculated by `mpi_montg_init(&mm, N)`.
  *                      This is -N^-1 mod 2^ciL.
  * \param[in,out]   T   A bignum for temporary storage.
- *                      It must be at least twice the limb size of N plus 2
- *                      (T->n >= 2 * (N->n + 1)).
+ *                      It must be at least twice the limb size of N plus 1
+ *                      (T->n >= 2 * N->n + 1).
  *                      Its initial content is unused and
  *                      its final content is indeterminate.
  *                      Note that unlike the usual convention in the library
@@ -1917,8 +1867,8 @@
 static void mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm,
                          const mbedtls_mpi *T )
 {
-    size_t i, n, m;
-    mbedtls_mpi_uint u0, u1, *d;
+    size_t n, m;
+    mbedtls_mpi_uint *d;
 
     memset( T->p, 0, T->n * ciL );
 
@@ -1926,18 +1876,23 @@
     n = N->n;
     m = ( B->n < n ) ? B->n : n;
 
-    for( i = 0; i < n; i++ )
+    for( size_t i = 0; i < n; i++ )
     {
+        mbedtls_mpi_uint u0, u1;
+
         /*
          * T = (T + u0*B + u1*N) / 2^biL
          */
         u0 = A->p[i];
         u1 = ( d[0] + u0 * B->p[0] ) * mm;
 
-        mpi_mul_hlp( m, B->p, d, u0 );
-        mpi_mul_hlp( n, N->p, d, u1 );
-
-        d++; d[n + 1] = 0;
+        (void) mbedtls_mpi_core_mla( d, n + 2,
+                                     B->p, m,
+                                     u0 );
+        (void) mbedtls_mpi_core_mla( d, n + 2,
+                                     N->p, n,
+                                     u1 );
+        d++;
     }
 
     /* At this point, d is either the desired result or the desired result
diff --git a/library/bignum_internal.h b/library/bignum_internal.h
new file mode 100644
index 0000000..8677dcf
--- /dev/null
+++ b/library/bignum_internal.h
@@ -0,0 +1,50 @@
+/**
+ *  Internal bignum functions
+ *
+ *  Copyright The Mbed TLS Contributors
+ *  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.
+ */
+
+#ifndef MBEDTLS_BIGNUM_INTERNAL_H
+#define MBEDTLS_BIGNUM_INTERNAL_H
+
+#include "common.h"
+
+#if defined(MBEDTLS_BIGNUM_C)
+#include "mbedtls/bignum.h"
+#endif
+
+/** Perform a known-size multiply accumulate operation
+ *
+ * Add \p b * \p s to \p d.
+ *
+ * \param[in,out] d     The pointer to the (little-endian) array
+ *                      representing the bignum to accumulate onto.
+ * \param d_len         The number of limbs of \p d. This must be
+ *                      at least \p s_len.
+ * \param[in] s         The pointer to the (little-endian) array
+ *                      representing the bignum to multiply with.
+ *                      This may be the same as \p d. Otherwise,
+ *                      it must be disjoint from \p d.
+ * \param s_len         The number of limbs of \p s.
+ * \param b             A scalar to multiply with.
+ *
+ * \return c            The carry at the end of the operation.
+ */
+mbedtls_mpi_uint mbedtls_mpi_core_mla( mbedtls_mpi_uint *d, size_t d_len ,
+                                       const mbedtls_mpi_uint *s, size_t s_len,
+                                       mbedtls_mpi_uint b );
+
+#endif /* MBEDTLS_BIGNUM_INTERNAL_H */
diff --git a/library/bn_mul.h b/library/bn_mul.h
index b71ddd8..962d7a9 100644
--- a/library/bn_mul.h
+++ b/library/bn_mul.h
@@ -98,7 +98,8 @@
  */
 #if defined(__i386__) && defined(__OPTIMIZE__)
 
-#define MULADDC_INIT                        \
+#define MULADDC_X1_INIT                     \
+    { mbedtls_mpi_uint t;                   \
     asm(                                    \
         "movl   %%ebx, %0           \n\t"   \
         "movl   %5, %%esi           \n\t"   \
@@ -106,7 +107,7 @@
         "movl   %7, %%ecx           \n\t"   \
         "movl   %8, %%ebx           \n\t"
 
-#define MULADDC_CORE                        \
+#define MULADDC_X1_CORE                     \
         "lodsl                      \n\t"   \
         "mull   %%ebx               \n\t"   \
         "addl   %%ecx,   %%eax      \n\t"   \
@@ -116,9 +117,21 @@
         "movl   %%edx,   %%ecx      \n\t"   \
         "stosl                      \n\t"
 
+#define MULADDC_X1_STOP                                 \
+        "movl   %4, %%ebx       \n\t"                   \
+        "movl   %%ecx, %1       \n\t"                   \
+        "movl   %%edi, %2       \n\t"                   \
+        "movl   %%esi, %3       \n\t"                   \
+        : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
+        : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
+        : "eax", "ebx", "ecx", "edx", "esi", "edi"      \
+    ); }
+
 #if defined(MBEDTLS_HAVE_SSE2)
 
-#define MULADDC_HUIT                            \
+#define MULADDC_X8_INIT MULADDC_X1_INIT
+
+#define MULADDC_X8_CORE                         \
         "movd     %%ecx,     %%mm1      \n\t"   \
         "movd     %%ebx,     %%mm0      \n\t"   \
         "movd     (%%edi),   %%mm3      \n\t"   \
@@ -181,7 +194,7 @@
         "psrlq    $32,       %%mm1      \n\t"   \
         "movd     %%mm1,     %%ecx      \n\t"
 
-#define MULADDC_STOP                    \
+#define MULADDC_X8_STOP                 \
         "emms                   \n\t"   \
         "movl   %4, %%ebx       \n\t"   \
         "movl   %%ecx, %1       \n\t"   \
@@ -190,29 +203,19 @@
         : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
         : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
         : "eax", "ebx", "ecx", "edx", "esi", "edi"      \
-    );
+    ); }                                                \
 
-#else
-
-#define MULADDC_STOP                    \
-        "movl   %4, %%ebx       \n\t"   \
-        "movl   %%ecx, %1       \n\t"   \
-        "movl   %%edi, %2       \n\t"   \
-        "movl   %%esi, %3       \n\t"   \
-        : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
-        : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
-        : "eax", "ebx", "ecx", "edx", "esi", "edi"      \
-    );
 #endif /* SSE2 */
+
 #endif /* i386 */
 
 #if defined(__amd64__) || defined (__x86_64__)
 
-#define MULADDC_INIT                        \
+#define MULADDC_X1_INIT                        \
     asm(                                    \
         "xorq   %%r8, %%r8\n"
 
-#define MULADDC_CORE                        \
+#define MULADDC_X1_CORE                        \
         "movq   (%%rsi), %%rax\n"           \
         "mulq   %%rbx\n"                    \
         "addq   $8, %%rsi\n"                \
@@ -224,7 +227,7 @@
         "adcq   %%rdx, %%rcx\n"             \
         "addq   $8, %%rdi\n"
 
-#define MULADDC_STOP                                                 \
+#define MULADDC_X1_STOP                                              \
         : "+c" (c), "+D" (d), "+S" (s), "+m" (*(uint64_t (*)[16]) d) \
         : "b" (b), "m" (*(const uint64_t (*)[16]) s)                 \
         : "rax", "rdx", "r8"                                         \
@@ -234,10 +237,10 @@
 
 #if defined(__aarch64__)
 
-#define MULADDC_INIT                \
+#define MULADDC_X1_INIT             \
     asm(
 
-#define MULADDC_CORE                \
+#define MULADDC_X1_CORE             \
         "ldr x4, [%2], #8   \n\t"   \
         "ldr x5, [%1]       \n\t"   \
         "mul x6, x4, %4     \n\t"   \
@@ -248,7 +251,7 @@
         "adc %0, x7, xzr    \n\t"   \
         "str x5, [%1], #8   \n\t"
 
-#define MULADDC_STOP                                                    \
+#define MULADDC_X1_STOP                                                 \
          : "+r" (c),  "+r" (d), "+r" (s), "+m" (*(uint64_t (*)[16]) d)  \
          : "r" (b), "m" (*(const uint64_t (*)[16]) s)                   \
          : "x4", "x5", "x6", "x7", "cc"                                 \
@@ -258,7 +261,7 @@
 
 #if defined(__mc68020__) || defined(__mcpu32__)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
     asm(                                \
         "movl   %3, %%a2        \n\t"   \
         "movl   %4, %%a3        \n\t"   \
@@ -266,7 +269,7 @@
         "movl   %6, %%d2        \n\t"   \
         "moveq  #0, %%d0        \n\t"
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
         "movel  %%a2@+, %%d1    \n\t"   \
         "mulul  %%d2, %%d4:%%d1 \n\t"   \
         "addl   %%d3, %%d1      \n\t"   \
@@ -275,7 +278,7 @@
         "addl   %%d1, %%a3@+    \n\t"   \
         "addxl  %%d4, %%d3      \n\t"
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
         "movl   %%d3, %0        \n\t"   \
         "movl   %%a3, %1        \n\t"   \
         "movl   %%a2, %2        \n\t"   \
@@ -284,7 +287,9 @@
         : "d0", "d1", "d2", "d3", "d4", "a2", "a3"  \
     );
 
-#define MULADDC_HUIT                        \
+#define MULADDC_X8_INIT MULADDC_X1_INIT
+
+#define MULADDC_X8_CORE                     \
         "movel  %%a2@+,  %%d1       \n\t"   \
         "mulul  %%d2,    %%d4:%%d1  \n\t"   \
         "addxl  %%d3,    %%d1       \n\t"   \
@@ -327,13 +332,15 @@
         "addl   %%d1,    %%a3@+     \n\t"   \
         "addxl  %%d0,    %%d3       \n\t"
 
+#define MULADDC_X8_STOP MULADDC_X1_STOP
+
 #endif /* MC68000 */
 
 #if defined(__powerpc64__) || defined(__ppc64__)
 
 #if defined(__MACH__) && defined(__APPLE__)
 
-#define MULADDC_INIT                        \
+#define MULADDC_X1_INIT                     \
     asm(                                    \
         "ld     r3, %3              \n\t"   \
         "ld     r4, %4              \n\t"   \
@@ -343,7 +350,7 @@
         "addi   r4, r4, -8          \n\t"   \
         "addic  r5, r5,  0          \n\t"
 
-#define MULADDC_CORE                        \
+#define MULADDC_X1_CORE                     \
         "ldu    r7, 8(r3)           \n\t"   \
         "mulld  r8, r7, r6          \n\t"   \
         "mulhdu r9, r7, r6          \n\t"   \
@@ -353,7 +360,7 @@
         "addc   r8, r8, r7          \n\t"   \
         "stdu   r8, 8(r4)           \n\t"
 
-#define MULADDC_STOP                        \
+#define MULADDC_X1_STOP                     \
         "addze  r5, r5              \n\t"   \
         "addi   r4, r4, 8           \n\t"   \
         "addi   r3, r3, 8           \n\t"   \
@@ -368,7 +375,7 @@
 
 #else /* __MACH__ && __APPLE__ */
 
-#define MULADDC_INIT                        \
+#define MULADDC_X1_INIT                     \
     asm(                                    \
         "ld     %%r3, %3            \n\t"   \
         "ld     %%r4, %4            \n\t"   \
@@ -378,7 +385,7 @@
         "addi   %%r4, %%r4, -8      \n\t"   \
         "addic  %%r5, %%r5,  0      \n\t"
 
-#define MULADDC_CORE                        \
+#define MULADDC_X1_CORE                     \
         "ldu    %%r7, 8(%%r3)       \n\t"   \
         "mulld  %%r8, %%r7, %%r6    \n\t"   \
         "mulhdu %%r9, %%r7, %%r6    \n\t"   \
@@ -388,7 +395,7 @@
         "addc   %%r8, %%r8, %%r7    \n\t"   \
         "stdu   %%r8, 8(%%r4)       \n\t"
 
-#define MULADDC_STOP                        \
+#define MULADDC_X1_STOP                     \
         "addze  %%r5, %%r5          \n\t"   \
         "addi   %%r4, %%r4, 8       \n\t"   \
         "addi   %%r3, %%r3, 8       \n\t"   \
@@ -406,7 +413,7 @@
 
 #if defined(__MACH__) && defined(__APPLE__)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
     asm(                                \
         "lwz    r3, %3          \n\t"   \
         "lwz    r4, %4          \n\t"   \
@@ -416,7 +423,7 @@
         "addi   r4, r4, -4      \n\t"   \
         "addic  r5, r5,  0      \n\t"
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
         "lwzu   r7, 4(r3)       \n\t"   \
         "mullw  r8, r7, r6      \n\t"   \
         "mulhwu r9, r7, r6      \n\t"   \
@@ -426,7 +433,7 @@
         "addc   r8, r8, r7      \n\t"   \
         "stwu   r8, 4(r4)       \n\t"
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
         "addze  r5, r5          \n\t"   \
         "addi   r4, r4, 4       \n\t"   \
         "addi   r3, r3, 4       \n\t"   \
@@ -440,7 +447,7 @@
 
 #else /* __MACH__ && __APPLE__ */
 
-#define MULADDC_INIT                        \
+#define MULADDC_X1_INIT                     \
     asm(                                    \
         "lwz    %%r3, %3            \n\t"   \
         "lwz    %%r4, %4            \n\t"   \
@@ -450,7 +457,7 @@
         "addi   %%r4, %%r4, -4      \n\t"   \
         "addic  %%r5, %%r5,  0      \n\t"
 
-#define MULADDC_CORE                        \
+#define MULADDC_X1_CORE                     \
         "lwzu   %%r7, 4(%%r3)       \n\t"   \
         "mullw  %%r8, %%r7, %%r6    \n\t"   \
         "mulhwu %%r9, %%r7, %%r6    \n\t"   \
@@ -460,7 +467,7 @@
         "addc   %%r8, %%r8, %%r7    \n\t"   \
         "stwu   %%r8, 4(%%r4)       \n\t"
 
-#define MULADDC_STOP                        \
+#define MULADDC_X1_STOP                     \
         "addze  %%r5, %%r5          \n\t"   \
         "addi   %%r4, %%r4, 4       \n\t"   \
         "addi   %%r3, %%r3, 4       \n\t"   \
@@ -483,14 +490,14 @@
 #if 0 && defined(__sparc__)
 #if defined(__sparc64__)
 
-#define MULADDC_INIT                                    \
+#define MULADDC_X1_INIT                                 \
     asm(                                                \
                 "ldx     %3, %%o0               \n\t"   \
                 "ldx     %4, %%o1               \n\t"   \
                 "ld      %5, %%o2               \n\t"   \
                 "ld      %6, %%o3               \n\t"
 
-#define MULADDC_CORE                                    \
+#define MULADDC_X1_CORE                                 \
                 "ld      [%%o0], %%o4           \n\t"   \
                 "inc     4, %%o0                \n\t"   \
                 "ld      [%%o1], %%o5           \n\t"   \
@@ -503,7 +510,7 @@
                 "addx    %%g1, 0, %%o2          \n\t"   \
                 "inc     4, %%o1                \n\t"
 
-        #define MULADDC_STOP                            \
+#define MULADDC_X1_STOP                                 \
                 "st      %%o2, %0               \n\t"   \
                 "stx     %%o1, %1               \n\t"   \
                 "stx     %%o0, %2               \n\t"   \
@@ -515,14 +522,14 @@
 
 #else /* __sparc64__ */
 
-#define MULADDC_INIT                                    \
+#define MULADDC_X1_INIT                                 \
     asm(                                                \
                 "ld      %3, %%o0               \n\t"   \
                 "ld      %4, %%o1               \n\t"   \
                 "ld      %5, %%o2               \n\t"   \
                 "ld      %6, %%o3               \n\t"
 
-#define MULADDC_CORE                                    \
+#define MULADDC_X1_CORE                                 \
                 "ld      [%%o0], %%o4           \n\t"   \
                 "inc     4, %%o0                \n\t"   \
                 "ld      [%%o1], %%o5           \n\t"   \
@@ -535,7 +542,7 @@
                 "addx    %%g1, 0, %%o2          \n\t"   \
                 "inc     4, %%o1                \n\t"
 
-#define MULADDC_STOP                                    \
+#define MULADDC_X1_STOP                                 \
                 "st      %%o2, %0               \n\t"   \
                 "st      %%o1, %1               \n\t"   \
                 "st      %%o0, %2               \n\t"   \
@@ -550,7 +557,7 @@
 
 #if defined(__microblaze__) || defined(microblaze)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
     asm(                                \
         "lwi   r3,   %3         \n\t"   \
         "lwi   r4,   %4         \n\t"   \
@@ -559,7 +566,7 @@
         "andi  r7,   r6, 0xffff \n\t"   \
         "bsrli r6,   r6, 16     \n\t"
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
         "lhui  r8,   r3,   0    \n\t"   \
         "addi  r3,   r3,   2    \n\t"   \
         "lhui  r9,   r3,   0    \n\t"   \
@@ -586,7 +593,7 @@
         "swi   r12,  r4,   0    \n\t"   \
         "addi   r4,  r4,   4    \n\t"
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
         "swi   r5,   %0         \n\t"   \
         "swi   r4,   %1         \n\t"   \
         "swi   r3,   %2         \n\t"   \
@@ -600,7 +607,7 @@
 
 #if defined(__tricore__)
 
-#define MULADDC_INIT                            \
+#define MULADDC_X1_INIT                         \
     asm(                                        \
         "ld.a   %%a2, %3                \n\t"   \
         "ld.a   %%a3, %4                \n\t"   \
@@ -608,7 +615,7 @@
         "ld.w   %%d1, %6                \n\t"   \
         "xor    %%d5, %%d5              \n\t"
 
-#define MULADDC_CORE                            \
+#define MULADDC_X1_CORE                         \
         "ld.w   %%d0,   [%%a2+]         \n\t"   \
         "madd.u %%e2, %%e4, %%d0, %%d1  \n\t"   \
         "ld.w   %%d0,   [%%a3]          \n\t"   \
@@ -617,7 +624,7 @@
         "mov    %%d4,    %%d3           \n\t"   \
         "st.w  [%%a3+],  %%d2           \n\t"
 
-#define MULADDC_STOP                            \
+#define MULADDC_X1_STOP                         \
         "st.w   %0, %%d4                \n\t"   \
         "st.a   %1, %%a3                \n\t"   \
         "st.a   %2, %%a2                \n\t"   \
@@ -647,7 +654,7 @@
 
 #if defined(__thumb__) && !defined(__thumb2__)
 
-#define MULADDC_INIT                                    \
+#define MULADDC_X1_INIT                                 \
     asm(                                                \
             "ldr    r0, %3                      \n\t"   \
             "ldr    r1, %4                      \n\t"   \
@@ -659,7 +666,7 @@
             "lsr    r7, r7, #16                 \n\t"   \
             "mov    r8, r7                      \n\t"
 
-#define MULADDC_CORE                                    \
+#define MULADDC_X1_CORE                                 \
             "ldmia  r0!, {r6}                   \n\t"   \
             "lsr    r7, r6, #16                 \n\t"   \
             "lsl    r6, r6, #16                 \n\t"   \
@@ -690,7 +697,7 @@
             "adc    r2, r5                      \n\t"   \
             "stmia  r1!, {r4}                   \n\t"
 
-#define MULADDC_STOP                                    \
+#define MULADDC_X1_STOP                                 \
             "str    r2, %0                      \n\t"   \
             "str    r1, %1                      \n\t"   \
             "str    r0, %2                      \n\t"   \
@@ -703,31 +710,79 @@
 #elif (__ARM_ARCH >= 6) && \
     defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1)
 
-#define MULADDC_INIT                            \
-    asm(
+#define MULADDC_X1_INIT                            \
+    {                                              \
+        mbedtls_mpi_uint tmp_a, tmp_b;             \
+        asm volatile (
 
-#define MULADDC_CORE                            \
-            "ldr    r0, [%0], #4        \n\t"   \
-            "ldr    r1, [%1]            \n\t"   \
-            "umaal  r1, %2, %3, r0      \n\t"   \
-            "str    r1, [%1], #4        \n\t"
+#define MULADDC_X1_CORE                                         \
+           ".p2align  2                                 \n\t"   \
+            "ldr.w    %[a], [%[in]], #4                 \n\t"   \
+            "ldr.w    %[b], [%[acc]]                    \n\t"   \
+            "umaal    %[b], %[carry], %[scalar], %[a]   \n\t"   \
+            "str.w    %[b], [%[acc]], #4                \n\t"
 
-#define MULADDC_STOP                            \
-         : "=r" (s),  "=r" (d), "=r" (c)        \
-         : "r" (b), "0" (s), "1" (d), "2" (c)   \
-         : "r0", "r1", "memory"                 \
-         );
+#define MULADDC_X1_STOP                                      \
+            : [a]      "=&r" (tmp_a),                        \
+              [b]      "=&r" (tmp_b),                        \
+              [in]     "+r"  (s),                            \
+              [acc]    "+r"  (d),                            \
+              [carry]  "+l"  (c)                             \
+            : [scalar] "r"   (b)                             \
+            : "memory"                                       \
+        );                                                   \
+    }
+
+#define MULADDC_X2_INIT                              \
+    {                                                \
+        mbedtls_mpi_uint tmp_a0, tmp_b0;             \
+        mbedtls_mpi_uint tmp_a1, tmp_b1;             \
+        asm volatile (
+
+            /* - Make sure loop is 4-byte aligned to avoid stalls
+             *   upon repeated non-word aligned instructions in
+             *   some microarchitectures.
+             * - Don't use ldm with post-increment or back-to-back
+             *   loads with post-increment and same address register
+             *   to avoid stalls on some microarchitectures.
+             * - Bunch loads and stores to reduce latency on some
+             *   microarchitectures. E.g., on Cortex-M4, the first
+             *   in a series of load/store operations has latency
+             *   2 cycles, while subsequent loads/stores are single-cycle. */
+#define MULADDC_X2_CORE                                           \
+           ".p2align  2                                   \n\t"   \
+            "ldr.w    %[a0], [%[in]],  #+8                \n\t"   \
+            "ldr.w    %[b0], [%[acc]], #+8                \n\t"   \
+            "ldr.w    %[a1], [%[in],  #-4]                \n\t"   \
+            "ldr.w    %[b1], [%[acc], #-4]                \n\t"   \
+            "umaal    %[b0], %[carry], %[scalar], %[a0]   \n\t"   \
+            "umaal    %[b1], %[carry], %[scalar], %[a1]   \n\t"   \
+            "str.w    %[b0], [%[acc], #-8]                \n\t"   \
+            "str.w    %[b1], [%[acc], #-4]                \n\t"
+
+#define MULADDC_X2_STOP                                      \
+            : [a0]     "=&r" (tmp_a0),                       \
+              [b0]     "=&r" (tmp_b0),                       \
+              [a1]     "=&r" (tmp_a1),                       \
+              [b1]     "=&r" (tmp_b1),                       \
+              [in]     "+r"  (s),                            \
+              [acc]    "+r"  (d),                            \
+              [carry]  "+l"  (c)                             \
+            : [scalar] "r"   (b)                             \
+            : "memory"                                       \
+        );                                                   \
+    }
 
 #else
 
-#define MULADDC_INIT                                    \
+#define MULADDC_X1_INIT                                 \
     asm(                                                \
             "ldr    r0, %3                      \n\t"   \
             "ldr    r1, %4                      \n\t"   \
             "ldr    r2, %5                      \n\t"   \
             "ldr    r3, %6                      \n\t"
 
-#define MULADDC_CORE                                    \
+#define MULADDC_X1_CORE                                 \
             "ldr    r4, [r0], #4                \n\t"   \
             "mov    r5, #0                      \n\t"   \
             "ldr    r6, [r1]                    \n\t"   \
@@ -736,7 +791,7 @@
             "adc    r2, r5, #0                  \n\t"   \
             "str    r7, [r1], #4                \n\t"
 
-#define MULADDC_STOP                                    \
+#define MULADDC_X1_STOP                                 \
             "str    r2, %0                      \n\t"   \
             "str    r1, %1                      \n\t"   \
             "str    r0, %2                      \n\t"   \
@@ -752,14 +807,14 @@
 
 #if defined(__alpha__)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
     asm(                                \
         "ldq    $1, %3          \n\t"   \
         "ldq    $2, %4          \n\t"   \
         "ldq    $3, %5          \n\t"   \
         "ldq    $4, %6          \n\t"
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
         "ldq    $6,  0($1)      \n\t"   \
         "addq   $1,  8, $1      \n\t"   \
         "mulq   $6, $4, $7      \n\t"   \
@@ -774,7 +829,7 @@
         "addq   $6, $3, $3      \n\t"   \
         "addq   $5, $3, $3      \n\t"
 
-#define MULADDC_STOP                                    \
+#define MULADDC_X1_STOP                 \
         "stq    $3, %0          \n\t"   \
         "stq    $2, %1          \n\t"   \
         "stq    $1, %2          \n\t"   \
@@ -786,14 +841,14 @@
 
 #if defined(__mips__) && !defined(__mips64)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
     asm(                                \
         "lw     $10, %3         \n\t"   \
         "lw     $11, %4         \n\t"   \
         "lw     $12, %5         \n\t"   \
         "lw     $13, %6         \n\t"
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
         "lw     $14, 0($10)     \n\t"   \
         "multu  $13, $14        \n\t"   \
         "addi   $10, $10, 4     \n\t"   \
@@ -809,7 +864,7 @@
         "addu   $12, $12, $14   \n\t"   \
         "addi   $11, $11, 4     \n\t"
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
         "sw     $12, %0         \n\t"   \
         "sw     $11, %1         \n\t"   \
         "sw     $10, %2         \n\t"   \
@@ -823,13 +878,13 @@
 
 #if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
 
-#define MULADDC_INIT                            \
+#define MULADDC_X1_INIT                         \
     __asm   mov     esi, s                      \
     __asm   mov     edi, d                      \
     __asm   mov     ecx, c                      \
     __asm   mov     ebx, b
 
-#define MULADDC_CORE                            \
+#define MULADDC_X1_CORE                         \
     __asm   lodsd                               \
     __asm   mul     ebx                         \
     __asm   add     eax, ecx                    \
@@ -839,11 +894,18 @@
     __asm   mov     ecx, edx                    \
     __asm   stosd
 
+#define MULADDC_X1_STOP                         \
+    __asm   mov     c, ecx                      \
+    __asm   mov     d, edi                      \
+    __asm   mov     s, esi
+
 #if defined(MBEDTLS_HAVE_SSE2)
 
 #define EMIT __asm _emit
 
-#define MULADDC_HUIT                            \
+#define MULADDC_X8_INIT MULADDC_X1_INIT
+
+#define MULADDC_X8_CORE                         \
     EMIT 0x0F  EMIT 0x6E  EMIT 0xC9             \
     EMIT 0x0F  EMIT 0x6E  EMIT 0xC3             \
     EMIT 0x0F  EMIT 0x6E  EMIT 0x1F             \
@@ -906,33 +968,26 @@
     EMIT 0x0F  EMIT 0x73  EMIT 0xD1  EMIT 0x20  \
     EMIT 0x0F  EMIT 0x7E  EMIT 0xC9
 
-#define MULADDC_STOP                            \
+#define MULADDC_X8_STOP                         \
     EMIT 0x0F  EMIT 0x77                        \
     __asm   mov     c, ecx                      \
     __asm   mov     d, edi                      \
-    __asm   mov     s, esi                      \
-
-#else
-
-#define MULADDC_STOP                            \
-    __asm   mov     c, ecx                      \
-    __asm   mov     d, edi                      \
-    __asm   mov     s, esi                      \
+    __asm   mov     s, esi
 
 #endif /* SSE2 */
 #endif /* MSVC */
 
 #endif /* MBEDTLS_HAVE_ASM */
 
-#if !defined(MULADDC_CORE)
+#if !defined(MULADDC_X1_CORE)
 #if defined(MBEDTLS_HAVE_UDBL)
 
-#define MULADDC_INIT                    \
+#define MULADDC_X1_INIT                 \
 {                                       \
     mbedtls_t_udbl r;                           \
     mbedtls_mpi_uint r0, r1;
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
     r   = *(s++) * (mbedtls_t_udbl) b;          \
     r0  = (mbedtls_mpi_uint) r;                   \
     r1  = (mbedtls_mpi_uint)( r >> biL );         \
@@ -940,18 +995,19 @@
     r0 += *d; r1 += (r0 < *d);          \
     c = r1; *(d++) = r0;
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
 }
 
-#else
-#define MULADDC_INIT                    \
+#else /* MBEDTLS_HAVE_UDBL */
+
+#define MULADDC_X1_INIT                 \
 {                                       \
     mbedtls_mpi_uint s0, s1, b0, b1;              \
     mbedtls_mpi_uint r0, r1, rx, ry;              \
     b0 = ( b << biH ) >> biH;           \
     b1 = ( b >> biH );
 
-#define MULADDC_CORE                    \
+#define MULADDC_X1_CORE                 \
     s0 = ( *s << biH ) >> biH;          \
     s1 = ( *s >> biH ); s++;            \
     rx = s0 * b1; r0 = s0 * b0;         \
@@ -965,10 +1021,28 @@
     r0 += *d; r1 += (r0 < *d);          \
     c = r1; *(d++) = r0;
 
-#define MULADDC_STOP                    \
+#define MULADDC_X1_STOP                 \
 }
 
-#endif /* C (generic)  */
 #endif /* C (longlong) */
+#endif /* C (generic)  */
+
+#if !defined(MULADDC_X2_CORE)
+#define MULADDC_X2_INIT MULADDC_X1_INIT
+#define MULADDC_X2_STOP MULADDC_X1_STOP
+#define MULADDC_X2_CORE MULADDC_X1_CORE MULADDC_X1_CORE
+#endif /* MULADDC_X2_CORE */
+
+#if !defined(MULADDC_X4_CORE)
+#define MULADDC_X4_INIT MULADDC_X2_INIT
+#define MULADDC_X4_STOP MULADDC_X2_STOP
+#define MULADDC_X4_CORE MULADDC_X2_CORE MULADDC_X2_CORE
+#endif /* MULADDC_X4_CORE */
+
+#if !defined(MULADDC_X8_CORE)
+#define MULADDC_X8_INIT MULADDC_X4_INIT
+#define MULADDC_X8_STOP MULADDC_X4_STOP
+#define MULADDC_X8_CORE MULADDC_X4_CORE MULADDC_X4_CORE
+#endif /* MULADDC_X8_CORE */
 
 #endif /* bn_mul.h */
diff --git a/library/ecp_curves.c b/library/ecp_curves.c
index 421a067..6b8ff5c 100644
--- a/library/ecp_curves.c
+++ b/library/ecp_curves.c
@@ -26,6 +26,7 @@
 #include "mbedtls/error.h"
 
 #include "bn_mul.h"
+#include "bignum_internal.h"
 #include "ecp_invasive.h"
 
 #include <string.h>
@@ -5213,40 +5214,30 @@
 
 /*
  * Fast quasi-reduction modulo p255 = 2^255 - 19
- * Write N as A0 + 2^255 A1, return A0 + 19 * A1
+ * Write N as A0 + 2^256 A1, return A0 + 38 * A1
  */
 static int ecp_mod_p255( mbedtls_mpi *N )
 {
-    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
-    size_t i;
-    mbedtls_mpi M;
-    mbedtls_mpi_uint Mp[P255_WIDTH + 2];
+    mbedtls_mpi_uint Mp[P255_WIDTH];
 
-    if( N->n < P255_WIDTH )
+    /* Helper references for top part of N */
+    mbedtls_mpi_uint * const NT_p = N->p + P255_WIDTH;
+    const size_t NT_n = N->n - P255_WIDTH;
+    if( N->n <= P255_WIDTH )
         return( 0 );
-
-    /* M = A1 */
-    M.s = 1;
-    M.n = N->n - ( P255_WIDTH - 1 );
-    if( M.n > P255_WIDTH + 1 )
+    if( NT_n > P255_WIDTH )
         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
-    M.p = Mp;
-    memset( Mp, 0, sizeof Mp );
-    memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
-    MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 255 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );
-    M.n++; /* Make room for multiplication by 19 */
 
-    /* N = A0 */
-    MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( N, 255, 0 ) );
-    for( i = P255_WIDTH; i < N->n; i++ )
-        N->p[i] = 0;
+    /* Split N as N + 2^256 M */
+    memcpy( Mp,   NT_p, sizeof( mbedtls_mpi_uint ) * NT_n );
+    memset( NT_p, 0,    sizeof( mbedtls_mpi_uint ) * NT_n );
 
-    /* N = A0 + 19 * A1 */
-    MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &M, 19 ) );
-    MBEDTLS_MPI_CHK( mbedtls_mpi_add_abs( N, N, &M ) );
+    /* N = A0 + 38 * A1 */
+    mbedtls_mpi_core_mla( N->p, P255_WIDTH + 1,
+                          Mp, NT_n,
+                          38 );
 
-cleanup:
-    return( ret );
+    return( 0 );
 }
 #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
 
diff --git a/library/pk.c b/library/pk.c
index 7f4d5fe..0f465cd 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -22,6 +22,7 @@
 #if defined(MBEDTLS_PK_C)
 #include "mbedtls/pk.h"
 #include "pk_wrap.h"
+#include "pkwrite.h"
 
 #include "mbedtls/platform_util.h"
 #include "mbedtls/error.h"
@@ -153,7 +154,7 @@
 int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx,
                              const mbedtls_svc_key_id_t key )
 {
-    const mbedtls_pk_info_t * const info = &mbedtls_pk_opaque_info;
+    const mbedtls_pk_info_t *info = NULL;
     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
     mbedtls_svc_key_id_t *pk_ctx;
     psa_key_type_t type;
@@ -166,9 +167,12 @@
     type = psa_get_key_type( &attributes );
     psa_reset_key_attributes( &attributes );
 
-    /* Current implementation of can_do() relies on this. */
-    if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
-        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ;
+    if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
+        info = &mbedtls_pk_ecdsa_opaque_info;
+    else if( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
+        info = &mbedtls_pk_rsa_opaque_info;
+    else
+        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
 
     if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL )
         return( MBEDTLS_ERR_PK_ALLOC_FAILED );
@@ -699,55 +703,100 @@
  * Load the key to a PSA key slot,
  * then turn the PK context into a wrapper for that key slot.
  *
- * Currently only works for EC private keys.
+ * Currently only works for EC & RSA private keys.
  */
 int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk,
                                mbedtls_svc_key_id_t *key,
                                psa_algorithm_t hash_alg )
 {
-#if !defined(MBEDTLS_ECP_C)
+#if !defined(MBEDTLS_ECP_C) && !defined(MBEDTLS_RSA_C)
     ((void) pk);
     ((void) key);
     ((void) hash_alg);
-    return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
 #else
-    const mbedtls_ecp_keypair *ec;
-    unsigned char d[MBEDTLS_ECP_MAX_BYTES];
-    size_t d_len;
-    psa_ecc_family_t curve_id;
-    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
-    psa_key_type_t key_type;
-    size_t bits;
-    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+#if defined(MBEDTLS_ECP_C)
+    if( mbedtls_pk_get_type( pk ) == MBEDTLS_PK_ECKEY )
+    {
+        const mbedtls_ecp_keypair *ec;
+        unsigned char d[MBEDTLS_ECP_MAX_BYTES];
+        size_t d_len;
+        psa_ecc_family_t curve_id;
+        psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+        psa_key_type_t key_type;
+        size_t bits;
+        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+        psa_status_t status;
 
-    /* export the private key material in the format PSA wants */
-    if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_ECKEY )
-        return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
+        /* export the private key material in the format PSA wants */
+        ec = mbedtls_pk_ec( *pk );
+        d_len = PSA_BITS_TO_BYTES( ec->grp.nbits );
+        if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 )
+            return( ret );
 
-    ec = mbedtls_pk_ec( *pk );
-    d_len = ( ec->grp.nbits + 7 ) / 8;
-    if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 )
-        return( ret );
+        curve_id = mbedtls_ecc_group_to_psa( ec->grp.id, &bits );
+        key_type = PSA_KEY_TYPE_ECC_KEY_PAIR( curve_id );
 
-    curve_id = mbedtls_ecc_group_to_psa( ec->grp.id, &bits );
-    key_type = PSA_KEY_TYPE_ECC_KEY_PAIR( curve_id );
+        /* prepare the key attributes */
+        psa_set_key_type( &attributes, key_type );
+        psa_set_key_bits( &attributes, bits );
+        psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH |
+                                              PSA_KEY_USAGE_DERIVE);
+        psa_set_key_algorithm( &attributes, PSA_ALG_ECDSA( hash_alg ) );
+        psa_set_key_enrollment_algorithm( &attributes, PSA_ALG_ECDH );
 
-    /* prepare the key attributes */
-    psa_set_key_type( &attributes, key_type );
-    psa_set_key_bits( &attributes, bits );
-    psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
-    psa_set_key_algorithm( &attributes, PSA_ALG_ECDSA(hash_alg) );
+        /* import private key into PSA */
+        status = psa_import_key( &attributes, d, d_len, key );
+        if( status != PSA_SUCCESS )
+            return( mbedtls_pk_error_from_psa( status ) );
 
-    /* import private key into PSA */
-    if( PSA_SUCCESS != psa_import_key( &attributes, d, d_len, key ) )
-        return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
+        /* make PK context wrap the key slot */
+        mbedtls_pk_free( pk );
+        mbedtls_pk_init( pk );
 
-    /* make PK context wrap the key slot */
-    mbedtls_pk_free( pk );
-    mbedtls_pk_init( pk );
-
-    return( mbedtls_pk_setup_opaque( pk, *key ) );
+        return( mbedtls_pk_setup_opaque( pk, *key ) );
+    }
+    else
 #endif /* MBEDTLS_ECP_C */
+#if defined(MBEDTLS_RSA_C)
+    if( mbedtls_pk_get_type( pk ) == MBEDTLS_PK_RSA )
+    {
+        unsigned char buf[MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES];
+        psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+        int key_len;
+        psa_status_t status;
+
+        /* export the private key material in the format PSA wants */
+        key_len = mbedtls_pk_write_key_der( pk, buf, sizeof( buf ) );
+        if( key_len <= 0 )
+            return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+
+        /* prepare the key attributes */
+        psa_set_key_type( &attributes, PSA_KEY_TYPE_RSA_KEY_PAIR );
+        psa_set_key_bits( &attributes, mbedtls_pk_get_bitlen( pk ) );
+        psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
+        psa_set_key_algorithm( &attributes,
+                               PSA_ALG_RSA_PKCS1V15_SIGN( hash_alg ) );
+
+        /* import private key into PSA */
+        status = psa_import_key( &attributes,
+                                 buf + sizeof( buf ) - key_len,
+                                 key_len, key);
+
+        mbedtls_platform_zeroize( buf, sizeof( buf ) );
+
+        if( status != PSA_SUCCESS )
+            return( mbedtls_pk_error_from_psa( status ) );
+
+        /* make PK context wrap the key slot */
+        mbedtls_pk_free( pk );
+        mbedtls_pk_init( pk );
+
+        return( mbedtls_pk_setup_opaque( pk, *key ) );
+    }
+    else
+#endif /* MBEDTLS_RSA_C */
+#endif /* !MBEDTLS_ECP_C && !MBEDTLS_RSA_C */
+    return( MBEDTLS_ERR_PK_TYPE_MISMATCH );
 }
 #endif /* MBEDTLS_USE_PSA_CRYPTO */
 #endif /* MBEDTLS_PK_C */
diff --git a/library/pk_wrap.c b/library/pk_wrap.c
index 2668290..a9c3c71 100644
--- a/library/pk_wrap.c
+++ b/library/pk_wrap.c
@@ -1493,21 +1493,23 @@
     return( bits );
 }
 
-static int pk_opaque_can_do( mbedtls_pk_type_t type )
+static int pk_opaque_ecdsa_can_do( mbedtls_pk_type_t type )
 {
-    /* For now opaque PSA keys can only wrap ECC keypairs,
-     * as checked by setup_psa().
-     * Also, ECKEY_DH does not really make sense with the current API. */
     return( type == MBEDTLS_PK_ECKEY ||
             type == MBEDTLS_PK_ECDSA );
 }
 
+static int pk_opaque_rsa_can_do( mbedtls_pk_type_t type )
+{
+    return( type == MBEDTLS_PK_RSA );
+}
+
 static int pk_opaque_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
                    const unsigned char *hash, size_t hash_len,
                    unsigned char *sig, size_t sig_size, size_t *sig_len,
                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
 {
-#if !defined(MBEDTLS_ECDSA_C)
+#if !defined(MBEDTLS_ECDSA_C) && !defined(MBEDTLS_RSA_C)
     ((void) ctx);
     ((void) md_alg);
     ((void) hash);
@@ -1518,31 +1520,92 @@
     ((void) f_rng);
     ((void) p_rng);
     return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
-#else /* !MBEDTLS_ECDSA_C */
+#else /* !MBEDTLS_ECDSA_C && !MBEDTLS_RSA_C */
     const mbedtls_svc_key_id_t *key = (const mbedtls_svc_key_id_t *) ctx;
-    psa_algorithm_t alg = PSA_ALG_ECDSA( mbedtls_psa_translate_md( md_alg ) );
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    psa_algorithm_t alg;
+    psa_key_type_t type;
     psa_status_t status;
 
     /* PSA has its own RNG */
     (void) f_rng;
     (void) p_rng;
 
+    status = psa_get_key_attributes( *key, &attributes );
+    if( status != PSA_SUCCESS )
+        return( mbedtls_pk_error_from_psa( status ) );
+
+    type = psa_get_key_type( &attributes );
+    psa_reset_key_attributes( &attributes );
+
+#if defined(MBEDTLS_ECDSA_C)
+    if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
+        alg = PSA_ALG_ECDSA( mbedtls_psa_translate_md( md_alg ) );
+    else
+#endif /* MBEDTLS_ECDSA_C */
+#if defined(MBEDTLS_RSA_C)
+    if( PSA_KEY_TYPE_IS_RSA( type ) )
+        alg = PSA_ALG_RSA_PKCS1V15_SIGN( mbedtls_psa_translate_md( md_alg ) );
+    else
+#endif /* MBEDTLS_RSA_C */
+        return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
+
     /* make the signature */
     status = psa_sign_hash( *key, alg, hash, hash_len,
                             sig, sig_size, sig_len );
     if( status != PSA_SUCCESS )
-        return( mbedtls_pk_error_from_psa_ecdsa( status ) );
+    {
+#if defined(MBEDTLS_ECDSA_C)
+        if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
+            return( mbedtls_pk_error_from_psa_ecdsa( status ) );
+        else
+#endif /* MBEDTLS_ECDSA_C */
+#if defined(MBEDTLS_RSA_C)
+        if( PSA_KEY_TYPE_IS_RSA( type ) )
+            return( mbedtls_pk_error_from_psa_rsa( status ) );
+        else
+#endif /* MBEDTLS_RSA_C */
+            return( mbedtls_pk_error_from_psa( status ) );
+    }
 
-    /* transcode it to ASN.1 sequence */
-    return( pk_ecdsa_sig_asn1_from_psa( sig, sig_len, sig_size ) );
-#endif /* !MBEDTLS_ECDSA_C */
+#if defined(MBEDTLS_ECDSA_C)
+    if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
+        /* transcode it to ASN.1 sequence */
+        return( pk_ecdsa_sig_asn1_from_psa( sig, sig_len, sig_size ) );
+#endif /* MBEDTLS_ECDSA_C */
+
+    return 0;
+#endif /* !MBEDTLS_ECDSA_C && !MBEDTLS_RSA_C */
 }
 
-const mbedtls_pk_info_t mbedtls_pk_opaque_info = {
+const mbedtls_pk_info_t mbedtls_pk_ecdsa_opaque_info = {
     MBEDTLS_PK_OPAQUE,
     "Opaque",
     pk_opaque_get_bitlen,
-    pk_opaque_can_do,
+    pk_opaque_ecdsa_can_do,
+    NULL, /* verify - will be done later */
+    pk_opaque_sign_wrap,
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+    NULL, /* restartable verify - not relevant */
+    NULL, /* restartable sign - not relevant */
+#endif
+    NULL, /* decrypt - not relevant */
+    NULL, /* encrypt - not relevant */
+    NULL, /* check_pair - could be done later or left NULL */
+    pk_opaque_alloc_wrap,
+    pk_opaque_free_wrap,
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+    NULL, /* restart alloc - not relevant */
+    NULL, /* restart free - not relevant */
+#endif
+    NULL, /* debug - could be done later, or even left NULL */
+};
+
+const mbedtls_pk_info_t mbedtls_pk_rsa_opaque_info = {
+    MBEDTLS_PK_OPAQUE,
+    "Opaque",
+    pk_opaque_get_bitlen,
+    pk_opaque_rsa_can_do,
     NULL, /* verify - will be done later */
     pk_opaque_sign_wrap,
 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
diff --git a/library/pk_wrap.h b/library/pk_wrap.h
index 1b490cc..5e81a65 100644
--- a/library/pk_wrap.h
+++ b/library/pk_wrap.h
@@ -136,7 +136,8 @@
 #endif
 
 #if defined(MBEDTLS_USE_PSA_CRYPTO)
-extern const mbedtls_pk_info_t mbedtls_pk_opaque_info;
+extern const mbedtls_pk_info_t mbedtls_pk_ecdsa_opaque_info;
+extern const mbedtls_pk_info_t mbedtls_pk_rsa_opaque_info;
 
 #if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
 int mbedtls_pk_error_from_psa_ecdsa( psa_status_t status );
diff --git a/library/pkwrite.c b/library/pkwrite.c
index 87285f0..8b99340 100644
--- a/library/pkwrite.c
+++ b/library/pkwrite.c
@@ -279,21 +279,35 @@
         bits = psa_get_key_bits( &attributes );
         psa_reset_key_attributes( &attributes );
 
-        curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type );
-        if( curve == 0 )
+        if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( key_type ) )
+        {
+            curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type );
+            if( curve == 0 )
+                return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
+
+            ret = mbedtls_psa_get_ecc_oid_from_id( curve, bits,
+                                                   &oid, &oid_len );
+            if( ret != 0 )
+                return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
+
+            /* Write EC algorithm parameters; that's akin
+             * to pk_write_ec_param() above. */
+            MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_oid( &c, buf,
+                                                                   oid,
+                                                                   oid_len ) );
+
+            /* The rest of the function works as for legacy EC contexts. */
+            pk_type = MBEDTLS_PK_ECKEY;
+        }
+        else if( PSA_KEY_TYPE_IS_RSA( key_type ) )
+        {
+            /* The rest of the function works as for legacy RSA contexts. */
+            pk_type = MBEDTLS_PK_RSA;
+        }
+        else
+        {
             return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
-
-        ret = mbedtls_psa_get_ecc_oid_from_id( curve, bits, &oid, &oid_len );
-        if( ret != 0 )
-            return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
-
-        /* Write EC algorithm parameters; that's akin
-         * to pk_write_ec_param() above. */
-        MBEDTLS_ASN1_CHK_ADD( par_len, mbedtls_asn1_write_oid( &c, buf,
-                                                               oid, oid_len ) );
-
-        /* The rest of the function works as for legacy EC contexts. */
-        pk_type = MBEDTLS_PK_ECKEY;
+        }
     }
 #endif /* MBEDTLS_USE_PSA_CRYPTO */
 
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index b2c2152..3262e09 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -2333,6 +2333,20 @@
         return( PSA_ERROR_INVALID_ARGUMENT );
     }
 
+    if( *mac_size > PSA_MAC_MAX_SIZE )
+    {
+        /* PSA_MAC_LENGTH returns the correct length even for a MAC algorithm
+         * that is disabled in the compile-time configuration. The result can
+         * therefore be larger than PSA_MAC_MAX_SIZE, which does take the
+         * configuration into account. In this case, force a return of
+         * PSA_ERROR_NOT_SUPPORTED here. Otherwise psa_mac_verify(), or
+         * psa_mac_compute(mac_size=PSA_MAC_MAX_SIZE), would return
+         * PSA_ERROR_BUFFER_TOO_SMALL for an unsupported algorithm whose MAC size
+         * is larger than PSA_MAC_MAX_SIZE, which is misleading and which breaks
+         * systematically generated tests. */
+        return( PSA_ERROR_NOT_SUPPORTED );
+    }
+
     return( PSA_SUCCESS );
 }
 
@@ -5019,50 +5033,75 @@
 /****************************************************************/
 
 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
+static int is_kdf_alg_supported( psa_algorithm_t kdf_alg )
+{
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
+    if( PSA_ALG_IS_HKDF( kdf_alg ) )
+        return( 1 );
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
+    if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
+        return( 1 );
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
+    if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
+        return( 1 );
+#endif
+    return( 0 );
+}
+
+static psa_status_t psa_hash_try_support( psa_algorithm_t alg )
+{
+    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
+    psa_status_t status = psa_hash_setup( &operation, alg );
+    psa_hash_abort( &operation );
+    return( status );
+}
+
 static psa_status_t psa_key_derivation_setup_kdf(
     psa_key_derivation_operation_t *operation,
     psa_algorithm_t kdf_alg )
 {
-    int is_kdf_alg_supported;
-
     /* Make sure that operation->ctx is properly zero-initialised. (Macro
      * initialisers for this union leave some bytes unspecified.) */
     memset( &operation->ctx, 0, sizeof( operation->ctx ) );
 
     /* Make sure that kdf_alg is a supported key derivation algorithm. */
-#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
-    if( PSA_ALG_IS_HKDF( kdf_alg ) )
-        is_kdf_alg_supported = 1;
-    else
-#endif
-#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
-    if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
-        is_kdf_alg_supported = 1;
-    else
-#endif
-#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
-    if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
-        is_kdf_alg_supported = 1;
-    else
-#endif
-    is_kdf_alg_supported = 0;
+    if( ! is_kdf_alg_supported( kdf_alg ) )
+        return( PSA_ERROR_NOT_SUPPORTED );
 
-    if( is_kdf_alg_supported )
+    /* All currently supported key derivation algorithms are based on a
+     * hash algorithm. */
+    psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
+    size_t hash_size = PSA_HASH_LENGTH( hash_alg );
+    if( hash_size == 0 )
+        return( PSA_ERROR_NOT_SUPPORTED );
+
+    /* Make sure that hash_alg is a supported hash algorithm. Otherwise
+     * we might fail later, which is somewhat unfriendly and potentially
+     * risk-prone. */
+    psa_status_t status = psa_hash_try_support( hash_alg );
+    if( status != PSA_SUCCESS )
+        return( status );
+
+    if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
+          PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
+        ! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
     {
-        psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
-        size_t hash_size = PSA_HASH_LENGTH( hash_alg );
-        if( hash_size == 0 )
-            return( PSA_ERROR_NOT_SUPPORTED );
-        if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
-              PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
-            ! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
-        {
-            return( PSA_ERROR_NOT_SUPPORTED );
-        }
-        operation->capacity = 255 * hash_size;
-        return( PSA_SUCCESS );
+        return( PSA_ERROR_NOT_SUPPORTED );
     }
 
+    operation->capacity = 255 * hash_size;
+    return( PSA_SUCCESS );
+}
+
+static psa_status_t psa_key_agreement_try_support( psa_algorithm_t alg )
+{
+#if defined(PSA_WANT_ALG_ECDH)
+    if( alg == PSA_ALG_ECDH )
+        return( PSA_SUCCESS );
+#endif
+    (void) alg;
     return( PSA_ERROR_NOT_SUPPORTED );
 }
 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
@@ -5081,6 +5120,10 @@
     {
 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF( alg );
+        psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE( alg );
+        status = psa_key_agreement_try_support( ka_alg );
+        if( status != PSA_SUCCESS )
+            return( status );
         status = psa_key_derivation_setup_kdf( operation, kdf_alg );
 #else
         return( PSA_ERROR_NOT_SUPPORTED );
diff --git a/library/psa_crypto_cipher.c b/library/psa_crypto_cipher.c
index ae30e5f..fafe68b 100644
--- a/library/psa_crypto_cipher.c
+++ b/library/psa_crypto_cipher.c
@@ -47,39 +47,61 @@
     {
         switch( alg )
         {
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER)
             case PSA_ALG_STREAM_CIPHER:
                 mode = MBEDTLS_MODE_STREAM;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CTR)
             case PSA_ALG_CTR:
                 mode = MBEDTLS_MODE_CTR;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CFB)
             case PSA_ALG_CFB:
                 mode = MBEDTLS_MODE_CFB;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_OFB)
             case PSA_ALG_OFB:
                 mode = MBEDTLS_MODE_OFB;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING)
             case PSA_ALG_ECB_NO_PADDING:
                 mode = MBEDTLS_MODE_ECB;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING)
             case PSA_ALG_CBC_NO_PADDING:
                 mode = MBEDTLS_MODE_CBC;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7)
             case PSA_ALG_CBC_PKCS7:
                 mode = MBEDTLS_MODE_CBC;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG)
             case PSA_ALG_CCM_STAR_NO_TAG:
                 mode = MBEDTLS_MODE_CCM_STAR_NO_TAG;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
             case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ):
                 mode = MBEDTLS_MODE_CCM;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
             case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ):
                 mode = MBEDTLS_MODE_GCM;
                 break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
             case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CHACHA20_POLY1305, 0 ):
                 mode = MBEDTLS_MODE_CHACHAPOLY;
                 break;
+#endif
             default:
                 return( NULL );
         }
@@ -91,12 +113,17 @@
 
     switch( key_type )
     {
+#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES)
         case PSA_KEY_TYPE_AES:
             cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
             break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ARIA)
         case PSA_KEY_TYPE_ARIA:
             cipher_id_tmp = MBEDTLS_CIPHER_ID_ARIA;
             break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
         case PSA_KEY_TYPE_DES:
             /* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
              * and 192 for three-key Triple-DES. */
@@ -110,12 +137,17 @@
             if( key_bits == 128 )
                 key_bits = 192;
             break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA)
         case PSA_KEY_TYPE_CAMELLIA:
             cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA;
             break;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20)
         case PSA_KEY_TYPE_CHACHA20:
             cipher_id_tmp = MBEDTLS_CIPHER_ID_CHACHA20;
             break;
+#endif
         default:
             return( NULL );
     }
@@ -239,6 +271,7 @@
                                        iv, iv_length ) ) );
 }
 
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING)
 /** Process input for which the algorithm is set to ECB mode.
  *
  * This requires manual processing, since the PSA API is defined as being
@@ -342,6 +375,7 @@
 exit:
     return( status );
 }
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING */
 
 psa_status_t mbedtls_psa_cipher_update(
     mbedtls_psa_cipher_operation_t *operation,
@@ -369,6 +403,7 @@
     if( output_size < expected_output_size )
         return( PSA_ERROR_BUFFER_TOO_SMALL );
 
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING)
     if( operation->alg == PSA_ALG_ECB_NO_PADDING )
     {
         /* mbedtls_cipher_update has an API inconsistency: it will only
@@ -381,6 +416,7 @@
                                         output_length );
     }
     else
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING */
     {
         status = mbedtls_to_psa_error(
             mbedtls_cipher_update( &operation->ctx.cipher, input,
diff --git a/library/ssl_misc.h b/library/ssl_misc.h
index 4964787..254627f 100644
--- a/library/ssl_misc.h
+++ b/library/ssl_misc.h
@@ -644,8 +644,9 @@
 
 #if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
     psa_key_type_t ecdh_psa_type;
-    uint16_t ecdh_bits;
+    size_t ecdh_bits;
     mbedtls_svc_key_id_t ecdh_psa_privkey;
+    uint8_t ecdh_psa_privkey_is_external;
     unsigned char ecdh_psa_peerkey[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
     size_t ecdh_psa_peerkey_len;
 #endif /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
@@ -2222,6 +2223,8 @@
             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
         case PSA_ERROR_BAD_STATE:
             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+        case PSA_ERROR_BUFFER_TOO_SMALL:
+            return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
         default:
             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
     }
diff --git a/library/ssl_msg.c b/library/ssl_msg.c
index 4eac24b..051e4b0 100644
--- a/library/ssl_msg.c
+++ b/library/ssl_msg.c
@@ -4855,6 +4855,9 @@
     if( ssl == NULL || ssl->conf == NULL )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
 
+    if( ssl->out_left != 0 )
+        return( mbedtls_ssl_flush_output( ssl ) );
+
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
     MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
 
@@ -5714,9 +5717,6 @@
 
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
 
-    if( ssl->out_left != 0 )
-        return( mbedtls_ssl_flush_output( ssl ) );
-
     if( mbedtls_ssl_is_handshake_over( ssl ) == 1 )
     {
         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 94cb776..3fc0701 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -1313,14 +1313,6 @@
 }
 
 #if defined(MBEDTLS_SSL_SRV_C)
-void mbedtls_ssl_conf_cert_cb( mbedtls_ssl_config *conf,
-                               int (*f_cert_cb)(mbedtls_ssl_context *) )
-{
-    conf->f_cert_cb = f_cert_cb;
-}
-#endif /* MBEDTLS_SSL_SRV_C */
-
-#if defined(MBEDTLS_SSL_SRV_C)
 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
                                      void *p_cache,
                                      mbedtls_ssl_cache_get_t *f_get_cache,
@@ -3204,7 +3196,8 @@
 
 #if defined(MBEDTLS_ECDH_C) && \
     ( defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3) )
-    psa_destroy_key( handshake->ecdh_psa_privkey );
+    if( handshake->ecdh_psa_privkey_is_external == 0 )
+        psa_destroy_key( handshake->ecdh_psa_privkey );
 #endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
diff --git a/library/ssl_tls12_client.c b/library/ssl_tls12_client.c
index 734d3a2..8250260 100644
--- a/library/ssl_tls12_client.c
+++ b/library/ssl_tls12_client.c
@@ -1813,6 +1813,7 @@
 
 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
+          defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||     \
           defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
 static int ssl_parse_server_ecdh_params_psa( mbedtls_ssl_context *ssl,
                                              unsigned char **p,
@@ -1861,9 +1862,7 @@
     {
         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
     }
-    if( ecdh_bits > 0xffff )
-        return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
-    handshake->ecdh_bits = (uint16_t) ecdh_bits;
+    handshake->ecdh_bits = ecdh_bits;
 
     /* Keep a copy of the peer's public key */
     ecpoint_len = *(*p)++;
@@ -2348,8 +2347,10 @@
           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
+          defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||      \
           defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
+        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
     {
         if( ssl_parse_server_ecdh_params_psa( ssl, &p, end ) != 0 )
@@ -2365,6 +2366,7 @@
     else
 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
             ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
+              MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
               MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */
 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
@@ -2998,6 +3000,162 @@
           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
+#if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
+    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
+    {
+        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
+        psa_key_attributes_t key_attributes;
+
+        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
+
+        /*
+         * opaque psk_identity<0..2^16-1>;
+         */
+        if( mbedtls_ssl_conf_has_static_psk( ssl->conf ) == 0 )
+            /* We don't offer PSK suites if we don't have a PSK,
+             * and we check that the server's choice is among the
+             * ciphersuites we offered, so this should never happen. */
+            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+
+        /* Opaque PSKs are currently only supported for PSK-only suites. */
+        if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 )
+            return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
+
+        /* uint16 to store content length */
+        const size_t content_len_size = 2;
+
+        header_len = 4;
+
+        if( header_len + content_len_size + ssl->conf->psk_identity_len
+                    > MBEDTLS_SSL_OUT_CONTENT_LEN )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1,
+                ( "psk identity too long or SSL buffer too short" ) );
+            return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
+        }
+
+        unsigned char *p = ssl->out_msg + header_len;
+
+        *p++ = MBEDTLS_BYTE_1( ssl->conf->psk_identity_len );
+        *p++ = MBEDTLS_BYTE_0( ssl->conf->psk_identity_len );
+        header_len += content_len_size;
+
+        memcpy( p, ssl->conf->psk_identity,
+                ssl->conf->psk_identity_len );
+        p += ssl->conf->psk_identity_len;
+
+        header_len += ssl->conf->psk_identity_len;
+
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Perform PSA-based ECDH computation." ) );
+
+        /*
+         * Generate EC private key for ECDHE exchange.
+         */
+
+        /* The master secret is obtained from the shared ECDH secret by
+         * applying the TLS 1.2 PRF with a specific salt and label. While
+         * the PSA Crypto API encourages combining key agreement schemes
+         * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
+         * yet support the provisioning of salt + label to the KDF.
+         * For the time being, we therefore need to split the computation
+         * of the ECDH secret and the application of the TLS 1.2 PRF. */
+        key_attributes = psa_key_attributes_init();
+        psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
+        psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH );
+        psa_set_key_type( &key_attributes, handshake->ecdh_psa_type );
+        psa_set_key_bits( &key_attributes, handshake->ecdh_bits );
+
+        /* Generate ECDH private key. */
+        status = psa_generate_key( &key_attributes,
+                                   &handshake->ecdh_psa_privkey );
+        if( status != PSA_SUCCESS )
+            return( psa_ssl_status_to_mbedtls( status ) );
+
+        /* Export the public part of the ECDH private key from PSA.
+         * The export format is an ECPoint structure as expected by TLS,
+         * but we just need to add a length byte before that. */
+        unsigned char *own_pubkey = p + 1;
+        unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
+        size_t own_pubkey_max_len = (size_t)( end - own_pubkey );
+        size_t own_pubkey_len = 0;
+
+        status = psa_export_public_key( handshake->ecdh_psa_privkey,
+                                        own_pubkey, own_pubkey_max_len,
+                                        &own_pubkey_len );
+        if( status != PSA_SUCCESS )
+        {
+            psa_destroy_key( handshake->ecdh_psa_privkey );
+            handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( psa_ssl_status_to_mbedtls( status ) );
+        }
+
+        *p = (unsigned char) own_pubkey_len;
+        content_len = own_pubkey_len + 1;
+
+        /* As RFC 5489 section 2, the premaster secret is formed as follows:
+         * - a uint16 containing the length (in octets) of the ECDH computation
+         * - the octet string produced by the ECDH computation
+         * - a uint16 containing the length (in octets) of the PSK
+         * - the PSK itself
+         */
+        unsigned char *pms = ssl->handshake->premaster;
+        const unsigned char* const pms_end = pms +
+                                sizeof( ssl->handshake->premaster );
+        /* uint16 to store length (in octets) of the ECDH computation */
+        const size_t zlen_size = 2;
+        size_t zlen = 0;
+
+        /* Perform ECDH computation after the uint16 reserved for the length */
+        status = psa_raw_key_agreement( PSA_ALG_ECDH,
+                                        handshake->ecdh_psa_privkey,
+                                        handshake->ecdh_psa_peerkey,
+                                        handshake->ecdh_psa_peerkey_len,
+                                        pms + zlen_size,
+                                        pms_end - ( pms + zlen_size ),
+                                        &zlen );
+
+        destruction_status = psa_destroy_key( handshake->ecdh_psa_privkey );
+        handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+
+        if( status != PSA_SUCCESS )
+            return( psa_ssl_status_to_mbedtls( status ) );
+        else if( destruction_status != PSA_SUCCESS )
+            return( psa_ssl_status_to_mbedtls( destruction_status ) );
+
+        /* Write the ECDH computation length before the ECDH computation */
+        MBEDTLS_PUT_UINT16_BE( zlen, pms, 0 );
+        pms += zlen_size + zlen;
+
+        const unsigned char *psk = NULL;
+        size_t psk_len = 0;
+
+        if( mbedtls_ssl_get_psk( ssl, &psk, &psk_len )
+                == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED )
+            /*
+             * This should never happen because the existence of a PSK is always
+             * checked before calling this function
+             */
+            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+
+        /* opaque psk<0..2^16-1>; */
+        if( (size_t)( pms_end - pms ) < ( 2 + psk_len ) )
+            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
+        /* Write the PSK length as uint16 */
+        MBEDTLS_PUT_UINT16_BE( psk_len, pms, 0 );
+        pms += 2;
+
+        /* Write the PSK itself */
+        memcpy( pms, psk, psk_len );
+        pms += psk_len;
+
+        ssl->handshake->pmslen = pms - ssl->handshake->premaster;
+    }
+    else
+#endif /* MBEDTLS_USE_PSA_CRYPTO &&
+          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
     if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
     {
diff --git a/library/ssl_tls12_server.c b/library/ssl_tls12_server.c
index 486632e..93cd0a5 100644
--- a/library/ssl_tls12_server.c
+++ b/library/ssl_tls12_server.c
@@ -2848,7 +2848,102 @@
 }
 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
 
-#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+#if defined(MBEDTLS_USE_PSA_CRYPTO) &&                      \
+        ( defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+          defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) )
+static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
+{
+    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+    unsigned char buf[
+        PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
+    psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
+    size_t ecdh_bits = 0;
+    size_t key_len;
+    mbedtls_pk_context *pk;
+    mbedtls_ecp_keypair *key;
+
+    pk = mbedtls_ssl_own_key( ssl );
+
+    if( pk == NULL )
+        return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
+
+    switch( mbedtls_pk_get_type( pk ) )
+    {
+    case MBEDTLS_PK_OPAQUE:
+        if( ! mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) )
+            return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
+
+        ssl->handshake->ecdh_psa_privkey =
+                *( (mbedtls_svc_key_id_t*) pk->pk_ctx );
+
+        /* Key should not be destroyed in the TLS library */
+        ssl->handshake->ecdh_psa_privkey_is_external = 1;
+
+        status = psa_get_key_attributes( ssl->handshake->ecdh_psa_privkey,
+                                         &key_attributes );
+        if( status != PSA_SUCCESS)
+        {
+            ssl->handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( psa_ssl_status_to_mbedtls( status ) );
+        }
+
+        ssl->handshake->ecdh_psa_type = psa_get_key_type( &key_attributes );
+        ssl->handshake->ecdh_bits = psa_get_key_bits( &key_attributes );
+
+        psa_reset_key_attributes( &key_attributes );
+
+        ret = 0;
+        break;
+    case MBEDTLS_PK_ECKEY:
+    case MBEDTLS_PK_ECKEY_DH:
+    case MBEDTLS_PK_ECDSA:
+        key = mbedtls_pk_ec( *pk );
+        if( key == NULL )
+            return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
+
+        /* Convert EC group to PSA key type. */
+        if( ( ssl->handshake->ecdh_psa_type =
+                    mbedtls_ecc_group_to_psa( key->grp.id,
+                                              &ecdh_bits ) ) == 0 )
+        {
+            return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+        }
+
+        ssl->handshake->ecdh_bits = ecdh_bits;
+
+        key_attributes = psa_key_attributes_init();
+        psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
+        psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH );
+        psa_set_key_type( &key_attributes,
+                PSA_KEY_TYPE_ECC_KEY_PAIR( ssl->handshake->ecdh_psa_type ) );
+        psa_set_key_bits( &key_attributes, ssl->handshake->ecdh_bits );
+
+        key_len = PSA_BITS_TO_BYTES( key->grp.pbits );
+        ret = mbedtls_ecp_write_key( key, buf, key_len );
+        if( ret != 0 )
+            goto cleanup;
+
+        status = psa_import_key( &key_attributes, buf, key_len,
+                                 &ssl->handshake->ecdh_psa_privkey );
+        if( status != PSA_SUCCESS )
+        {
+            ret = psa_ssl_status_to_mbedtls( status );
+            goto cleanup;
+        }
+
+        ret = 0;
+        break;
+    default:
+            ret = MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
+    }
+
+cleanup:
+    mbedtls_platform_zeroize( buf, sizeof( buf ) );
+
+    return( ret );
+}
+#elif defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
 {
@@ -3068,7 +3163,8 @@
 
 #if defined(MBEDTLS_USE_PSA_CRYPTO)
         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
-            ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
+            ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
+            ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
         {
             psa_status_t status = PSA_ERROR_GENERIC_ERROR;
             psa_key_attributes_t key_attributes;
@@ -3085,12 +3181,12 @@
             handshake->ecdh_psa_type = mbedtls_psa_parse_tls_ecc_group(
                         (*curve)->tls_id, &ecdh_bits );
 
-            if( handshake->ecdh_psa_type == 0 || ecdh_bits > 0xffff )
+            if( handshake->ecdh_psa_type == 0 )
             {
                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Invalid ecc group parse." ) );
                 return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
             }
-            handshake->ecdh_bits = (uint16_t) ecdh_bits;
+            handshake->ecdh_bits = ecdh_bits;
 
             key_attributes = psa_key_attributes_init();
             psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
@@ -3832,9 +3928,13 @@
 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
-          defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
+          defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||   \
+          defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||      \
+          defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) )
     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
-        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
+        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
+        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
+        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
     {
         size_t data_len = (size_t)( *p++ );
         size_t buf_len = (size_t)( end - p );
@@ -3872,25 +3972,31 @@
         {
             ret = psa_ssl_status_to_mbedtls( status );
             MBEDTLS_SSL_DEBUG_RET( 1, "psa_raw_key_agreement", ret );
-            (void) psa_destroy_key( handshake->ecdh_psa_privkey );
+            if( handshake->ecdh_psa_privkey_is_external == 0 )
+                (void) psa_destroy_key( handshake->ecdh_psa_privkey );
             handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
             return( ret );
         }
 
-        status = psa_destroy_key( handshake->ecdh_psa_privkey );
-
-        if( status != PSA_SUCCESS )
+        if( handshake->ecdh_psa_privkey_is_external == 0 )
         {
-            ret = psa_ssl_status_to_mbedtls( status );
-            MBEDTLS_SSL_DEBUG_RET( 1, "psa_destroy_key", ret );
-            return( ret );
+            status = psa_destroy_key( handshake->ecdh_psa_privkey );
+
+            if( status != PSA_SUCCESS )
+            {
+                ret = psa_ssl_status_to_mbedtls( status );
+                MBEDTLS_SSL_DEBUG_RET( 1, "psa_destroy_key", ret );
+                return( ret );
+            }
         }
         handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
     }
     else
 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
             ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
-              MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */
+              MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
+              MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
+              MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED ) */
 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
@@ -4037,6 +4143,115 @@
     }
     else
 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
+#if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
+        defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
+    if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
+    {
+        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
+        uint8_t ecpoint_len;
+
+        /* Opaque PSKs are currently only supported for PSK-only. */
+        if( ssl_use_opaque_psk( ssl ) == 1 )
+            return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
+
+        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
+
+        if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
+        {
+            MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
+            psa_destroy_key( handshake->ecdh_psa_privkey );
+            handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( ret );
+        }
+
+        /* Keep a copy of the peer's public key */
+        if( p >= end )
+        {
+            psa_destroy_key( handshake->ecdh_psa_privkey );
+            handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( MBEDTLS_ERR_SSL_DECODE_ERROR );
+        }
+
+        ecpoint_len = *(p++);
+        if( (size_t)( end - p ) < ecpoint_len ) {
+            psa_destroy_key( handshake->ecdh_psa_privkey );
+            handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( MBEDTLS_ERR_SSL_DECODE_ERROR );
+        }
+
+        if( ecpoint_len > sizeof( handshake->ecdh_psa_peerkey ) ) {
+            psa_destroy_key( handshake->ecdh_psa_privkey );
+            handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+            return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+        }
+
+        memcpy( handshake->ecdh_psa_peerkey, p, ecpoint_len );
+        handshake->ecdh_psa_peerkey_len = ecpoint_len;
+        p += ecpoint_len;
+
+        /* As RFC 5489 section 2, the premaster secret is formed as follows:
+         * - a uint16 containing the length (in octets) of the ECDH computation
+         * - the octet string produced by the ECDH computation
+         * - a uint16 containing the length (in octets) of the PSK
+         * - the PSK itself
+         */
+        unsigned char *psm = ssl->handshake->premaster;
+        const unsigned char* const psm_end =
+                    psm + sizeof( ssl->handshake->premaster );
+        /* uint16 to store length (in octets) of the ECDH computation */
+        const size_t zlen_size = 2;
+        size_t zlen = 0;
+
+        /* Compute ECDH shared secret. */
+        status = psa_raw_key_agreement( PSA_ALG_ECDH,
+                                        handshake->ecdh_psa_privkey,
+                                        handshake->ecdh_psa_peerkey,
+                                        handshake->ecdh_psa_peerkey_len,
+                                        psm + zlen_size,
+                                        psm_end - ( psm + zlen_size ),
+                                        &zlen );
+
+        destruction_status = psa_destroy_key( handshake->ecdh_psa_privkey );
+        handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
+
+        if( status != PSA_SUCCESS )
+            return( psa_ssl_status_to_mbedtls( status ) );
+        else if( destruction_status != PSA_SUCCESS )
+            return( psa_ssl_status_to_mbedtls( destruction_status ) );
+
+        /* Write the ECDH computation length before the ECDH computation */
+        MBEDTLS_PUT_UINT16_BE( zlen, psm, 0 );
+        psm += zlen_size + zlen;
+
+        const unsigned char *psk = NULL;
+        size_t psk_len = 0;
+
+        if( mbedtls_ssl_get_psk( ssl, &psk, &psk_len )
+                == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED )
+            /*
+             * This should never happen because the existence of a PSK is always
+             * checked before calling this function
+             */
+            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+
+        /* opaque psk<0..2^16-1>; */
+        if( (size_t)( psm_end - psm ) < ( 2 + psk_len ) )
+            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
+        /* Write the PSK length as uint16 */
+        MBEDTLS_PUT_UINT16_BE( psk_len, psm, 0 );
+        psm += 2;
+
+        /* Write the PSK itself */
+        memcpy( psm, psk, psk_len );
+        psm += psk_len;
+
+        ssl->handshake->pmslen = psm - ssl->handshake->premaster;
+    }
+    else
+#endif /* MBEDTLS_USE_PSA_CRYPTO &&
+            MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
     {
diff --git a/library/ssl_tls13_client.c b/library/ssl_tls13_client.c
index 3bb308c..8e1112d 100644
--- a/library/ssl_tls13_client.c
+++ b/library/ssl_tls13_client.c
@@ -229,9 +229,7 @@
         mbedtls_psa_parse_tls_ecc_group( named_group, &ecdh_bits ) ) == 0 )
             return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
 
-    if( ecdh_bits > 0xffff )
-        return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
-    ssl->handshake->ecdh_bits = (uint16_t) ecdh_bits;
+    ssl->handshake->ecdh_bits = ecdh_bits;
 
     key_attributes = psa_key_attributes_init();
     psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
@@ -262,12 +260,6 @@
 
     }
 
-    if( own_pubkey_len > (size_t)( end - buf ) )
-    {
-            MBEDTLS_SSL_DEBUG_MSG( 1, ( "No space in the buffer for ECDH public key." ) );
-        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
-    }
-
     *out_len = own_pubkey_len;
 
     return( 0 );
diff --git a/library/timing.c b/library/timing.c
index a65bc99..859c1b8 100644
--- a/library/timing.c
+++ b/library/timing.c
@@ -46,14 +46,14 @@
 #include <unistd.h>
 #include <sys/types.h>
 #include <signal.h>
-#if defined(MBEDTLS_HAVE_TIME)
+/* time.h should be included independently of MBEDTLS_HAVE_TIME. If the
+ * platform matches the ifdefs above, it will be used. */
 #include <time.h>
 #include <sys/time.h>
 struct _hr_time
 {
     struct timeval start;
 };
-#endif
 #endif /* _WIN32 && !EFIX64 && !EFI32 */
 
 /**
@@ -75,7 +75,6 @@
  *                 get_timer(0) }` the value time1+time2 is only approximately
  *                 the delay since the first reset.
  */
-#if defined(MBEDTLS_HAVE_TIME)
 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
 
 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
@@ -167,33 +166,5 @@
 {
     return( data->fin_ms );
 }
-#else /* MBEDTLS_HAVE_TIME */
-uint32_t mbedtls_timing_get_final_delay(
-                                      const mbedtls_timing_delay_context *data )
-{
-    (void) data;
-    return( 0 );
-}
-
-int mbedtls_timing_get_delay( void *data )
-{
-    (void) data;
-    return( 0 );
-}
-void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )
-{
-    (void) data;
-    (void) int_ms;
-    (void) fin_ms;
-}
-
-unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
-{
-    (void) val;
-    (void) reset;
-    return( 0 );
-}
-
-#endif /* MBEDTLS_HAVE_TIME */
 #endif /* !MBEDTLS_TIMING_ALT */
 #endif /* MBEDTLS_TIMING_C */
diff --git a/programs/test/selftest.c b/programs/test/selftest.c
index c7bcc53..0c40686 100644
--- a/programs/test/selftest.c
+++ b/programs/test/selftest.c
@@ -49,7 +49,9 @@
 #include "mbedtls/ecjpake.h"
 #include "mbedtls/timing.h"
 #include "mbedtls/nist_kw.h"
+#include "mbedtls/debug.h"
 
+#include <limits.h>
 #include <string.h>
 
 #if defined(MBEDTLS_PLATFORM_C)
@@ -361,6 +363,78 @@
     }
 
     /*
+     * The C standard allows padding bits in the representation
+     * of standard integer types, but our code does currently not
+     * support them.
+     *
+     * Here we check that the underlying C implementation doesn't
+     * use padding bits, and fail cleanly if it does.
+     *
+     * The check works by casting the maximum value representable
+     * by a given integer type into the unpadded integer type of the
+     * same bit-width and checking that it agrees with the maximum value
+     * of that unpadded type. For example, for a 4-byte int,
+     * MAX_INT should be 0x7fffffff in int32_t. This assumes that
+     * CHAR_BIT == 8, which is checked in check_config.h.
+     *
+     * We assume that [u]intxx_t exist and that they don't
+     * have padding bits, as the standard requires.
+     */
+
+#define CHECK_PADDING_SIGNED(TYPE, NAME)                                \
+    do                                                                  \
+    {                                                                   \
+        if( sizeof( TYPE ) == 2 || sizeof( TYPE ) == 4 ||               \
+                sizeof( TYPE ) == 8 ) {                                 \
+            if( ( sizeof( TYPE ) == 2 &&                                \
+                (int16_t) NAME ## _MAX != 0x7FFF )             ||       \
+                ( sizeof( TYPE ) == 4 &&                                \
+                (int32_t) NAME ## _MAX != 0x7FFFFFFF )         ||       \
+                ( sizeof( TYPE ) == 8 &&                                \
+                (int64_t) NAME ## _MAX != 0x7FFFFFFFFFFFFFFF ) )        \
+            {                                                           \
+                mbedtls_printf( "Type '" #TYPE "' has padding bits\n" );\
+                mbedtls_exit( MBEDTLS_EXIT_FAILURE );                   \
+            }                                                           \
+        } else {                                                        \
+            mbedtls_printf( "Padding checks only implemented for types of size 2, 4 or 8" \
+                " - cannot check type '" #TYPE "' of size %" MBEDTLS_PRINTF_SIZET "\n",       \
+                sizeof( TYPE ) );                                       \
+            mbedtls_exit( MBEDTLS_EXIT_FAILURE );                       \
+        }                                                               \
+    } while( 0 )
+
+#define CHECK_PADDING_UNSIGNED(TYPE, NAME)                              \
+    do                                                                  \
+    {                                                                   \
+        if( ( sizeof( TYPE ) == 2 &&                                    \
+              (uint16_t) NAME ## _MAX != 0xFFFF )             ||        \
+            ( sizeof( TYPE ) == 4 &&                                    \
+              (uint32_t) NAME ## _MAX != 0xFFFFFFFF )         ||        \
+            ( sizeof( TYPE ) == 8 &&                                    \
+              (uint64_t) NAME ## _MAX != 0xFFFFFFFFFFFFFFFF ) )         \
+        {                                                               \
+            mbedtls_printf( "Type '" #TYPE "' has padding bits\n" );    \
+            mbedtls_exit( MBEDTLS_EXIT_FAILURE );                       \
+        }                                                               \
+    } while( 0 )
+
+    CHECK_PADDING_SIGNED( short,        SHRT );
+    CHECK_PADDING_SIGNED( int,           INT );
+    CHECK_PADDING_SIGNED( long,         LONG );
+    CHECK_PADDING_SIGNED( long long,   LLONG );
+    CHECK_PADDING_SIGNED( ptrdiff_t, PTRDIFF );
+
+    CHECK_PADDING_UNSIGNED( unsigned short,      USHRT );
+    CHECK_PADDING_UNSIGNED( unsigned,             UINT );
+    CHECK_PADDING_UNSIGNED( unsigned long,       ULONG );
+    CHECK_PADDING_UNSIGNED( unsigned long long, ULLONG );
+    CHECK_PADDING_UNSIGNED( size_t,               SIZE );
+
+#undef CHECK_PADDING_SIGNED
+#undef CHECK_PADDING_UNSIGNED
+
+    /*
      * Make sure we have a snprintf that correctly zero-terminates
      */
     if( run_test_snprintf() != 0 )
diff --git a/programs/test/udp_proxy.c b/programs/test/udp_proxy.c
index bc78fab..41a90a9 100644
--- a/programs/test/udp_proxy.c
+++ b/programs/test/udp_proxy.c
@@ -825,7 +825,6 @@
 
     get_options( argc, argv );
 
-#if defined(MBEDTLS_HAVE_TIME)
     /*
      * Decisions to drop/delay/duplicate packets are pseudo-random: dropping
      * exactly 1 in N packets would lead to problems when a flight has exactly
@@ -836,12 +835,15 @@
      */
     if( opt.seed == 0 )
     {
+#if defined(MBEDTLS_HAVE_TIME)
         opt.seed = (unsigned int) mbedtls_time( NULL );
+#else
+        opt.seed = 1;
+#endif /* MBEDTLS_HAVE_TIME */
         mbedtls_printf( "  . Pseudo-random seed: %u\n", opt.seed );
     }
 
     srand( opt.seed );
-#endif /* MBEDTLS_HAVE_TIME */
 
     /*
      * 0. "Connect" to the server
diff --git a/scripts/mbedtls_dev/crypto_knowledge.py b/scripts/mbedtls_dev/crypto_knowledge.py
index c38955b..1bd011f 100644
--- a/scripts/mbedtls_dev/crypto_knowledge.py
+++ b/scripts/mbedtls_dev/crypto_knowledge.py
@@ -18,15 +18,45 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import enum
 import re
 from typing import Dict, Iterable, Optional, Pattern, Tuple
 
 from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
 
+
+BLOCK_CIPHERS = frozenset(['AES', 'ARIA', 'CAMELLIA', 'DES'])
+BLOCK_MAC_MODES = frozenset(['CBC_MAC', 'CMAC'])
+BLOCK_CIPHER_MODES = frozenset([
+    'CTR', 'CFB', 'OFB', 'XTS', 'CCM_STAR_NO_TAG',
+    'ECB_NO_PADDING', 'CBC_NO_PADDING', 'CBC_PKCS7',
+])
+BLOCK_AEAD_MODES = frozenset(['CCM', 'GCM'])
+
+class EllipticCurveCategory(enum.Enum):
+    """Categorization of elliptic curve families.
+
+    The category of a curve determines what algorithms are defined over it.
+    """
+
+    SHORT_WEIERSTRASS = 0
+    MONTGOMERY = 1
+    TWISTED_EDWARDS = 2
+
+    @staticmethod
+    def from_family(family: str) -> 'EllipticCurveCategory':
+        if family == 'PSA_ECC_FAMILY_MONTGOMERY':
+            return EllipticCurveCategory.MONTGOMERY
+        if family == 'PSA_ECC_FAMILY_TWISTED_EDWARDS':
+            return EllipticCurveCategory.TWISTED_EDWARDS
+        # Default to SW, which most curves belong to.
+        return EllipticCurveCategory.SHORT_WEIERSTRASS
+
+
 class KeyType:
     """Knowledge about a PSA key type."""
 
-    def __init__(self, name: str, params: Optional[Iterable[str]] = None):
+    def __init__(self, name: str, params: Optional[Iterable[str]] = None) -> None:
         """Analyze a key type.
 
         The key type must be specified in PSA syntax. In its simplest form,
@@ -62,6 +92,11 @@
         if self.params is not None:
             self.expression += '(' + ', '.join(self.params) + ')'
 
+        m = re.match(r'PSA_KEY_TYPE_(\w+)', self.name)
+        assert m
+        self.head = re.sub(r'_(?:PUBLIC_KEY|KEY_PAIR)\Z', r'', m.group(1))
+        """The key type macro name, with common prefixes and suffixes stripped."""
+
         self.private_type = re.sub(r'_PUBLIC_KEY\Z', r'_KEY_PAIR', self.name)
         """The key type macro name for the corresponding key pair type.
 
@@ -69,6 +104,10 @@
         `self.name`.
         """
 
+    def is_public(self) -> bool:
+        """Whether the key type is for public keys."""
+        return self.name.endswith('_PUBLIC_KEY')
+
     ECC_KEY_SIZES = {
         'PSA_ECC_FAMILY_SECP_K1': (192, 224, 256),
         'PSA_ECC_FAMILY_SECP_R1': (225, 256, 384, 521),
@@ -153,3 +192,210 @@
         """
         # This is just temporaly solution for the implicit usage flags.
         return re.match(self.KEY_TYPE_FOR_SIGNATURE[usage], self.name) is not None
+
+    def can_do(self, alg: 'Algorithm') -> bool:
+        """Whether this key type can be used for operations with the given algorithm.
+
+        This function does not currently handle key derivation or PAKE.
+        """
+        #pylint: disable=too-many-return-statements
+        if alg.is_wildcard:
+            return False
+        if self.head == 'HMAC' and alg.head == 'HMAC':
+            return True
+        if self.head in BLOCK_CIPHERS and \
+           alg.head in frozenset.union(BLOCK_MAC_MODES,
+                                       BLOCK_CIPHER_MODES,
+                                       BLOCK_AEAD_MODES):
+            return True
+        if self.head == 'CHACHA20' and alg.head == 'CHACHA20_POLY1305':
+            return True
+        if self.head in {'ARC4', 'CHACHA20'} and \
+           alg.head == 'STREAM_CIPHER':
+            return True
+        if self.head == 'RSA' and alg.head.startswith('RSA_'):
+            return True
+        if self.head == 'ECC':
+            assert self.params is not None
+            eccc = EllipticCurveCategory.from_family(self.params[0])
+            if alg.head == 'ECDH' and \
+               eccc in {EllipticCurveCategory.SHORT_WEIERSTRASS,
+                        EllipticCurveCategory.MONTGOMERY}:
+                return True
+            if alg.head == 'ECDSA' and \
+               eccc == EllipticCurveCategory.SHORT_WEIERSTRASS:
+                return True
+            if alg.head in {'PURE_EDDSA', 'EDDSA_PREHASH'} and \
+               eccc == EllipticCurveCategory.TWISTED_EDWARDS:
+                return True
+        return False
+
+
+class AlgorithmCategory(enum.Enum):
+    """PSA algorithm categories."""
+    # The numbers are aligned with the category bits in numerical values of
+    # algorithms.
+    HASH = 2
+    MAC = 3
+    CIPHER = 4
+    AEAD = 5
+    SIGN = 6
+    ASYMMETRIC_ENCRYPTION = 7
+    KEY_DERIVATION = 8
+    KEY_AGREEMENT = 9
+    PAKE = 10
+
+    def requires_key(self) -> bool:
+        """Whether operations in this category are set up with a key."""
+        return self not in {self.HASH, self.KEY_DERIVATION}
+
+    def is_asymmetric(self) -> bool:
+        """Whether operations in this category involve asymmetric keys."""
+        return self in {
+            self.SIGN,
+            self.ASYMMETRIC_ENCRYPTION,
+            self.KEY_AGREEMENT
+        }
+
+
+class AlgorithmNotRecognized(Exception):
+    def __init__(self, expr: str) -> None:
+        super().__init__('Algorithm not recognized: ' + expr)
+        self.expr = expr
+
+
+class Algorithm:
+    """Knowledge about a PSA algorithm."""
+
+    @staticmethod
+    def determine_base(expr: str) -> str:
+        """Return an expression for the "base" of the algorithm.
+
+        This strips off variants of algorithms such as MAC truncation.
+
+        This function does not attempt to detect invalid inputs.
+        """
+        m = re.match(r'PSA_ALG_(?:'
+                     r'(?:TRUNCATED|AT_LEAST_THIS_LENGTH)_MAC|'
+                     r'AEAD_WITH_(?:SHORTENED|AT_LEAST_THIS_LENGTH)_TAG'
+                     r')\((.*),[^,]+\)\Z', expr)
+        if m:
+            expr = m.group(1)
+        return expr
+
+    @staticmethod
+    def determine_head(expr: str) -> str:
+        """Return the head of an algorithm expression.
+
+        The head is the first (outermost) constructor, without its PSA_ALG_
+        prefix, and with some normalization of similar algorithms.
+        """
+        m = re.match(r'PSA_ALG_(?:DETERMINISTIC_)?(\w+)', expr)
+        if not m:
+            raise AlgorithmNotRecognized(expr)
+        head = m.group(1)
+        if head == 'KEY_AGREEMENT':
+            m = re.match(r'PSA_ALG_KEY_AGREEMENT\s*\(\s*PSA_ALG_(\w+)', expr)
+            if not m:
+                raise AlgorithmNotRecognized(expr)
+            head = m.group(1)
+        head = re.sub(r'_ANY\Z', r'', head)
+        if re.match(r'ED[0-9]+PH\Z', head):
+            head = 'EDDSA_PREHASH'
+        return head
+
+    CATEGORY_FROM_HEAD = {
+        'SHA': AlgorithmCategory.HASH,
+        'SHAKE256_512': AlgorithmCategory.HASH,
+        'MD': AlgorithmCategory.HASH,
+        'RIPEMD': AlgorithmCategory.HASH,
+        'ANY_HASH': AlgorithmCategory.HASH,
+        'HMAC': AlgorithmCategory.MAC,
+        'STREAM_CIPHER': AlgorithmCategory.CIPHER,
+        'CHACHA20_POLY1305': AlgorithmCategory.AEAD,
+        'DSA': AlgorithmCategory.SIGN,
+        'ECDSA': AlgorithmCategory.SIGN,
+        'EDDSA': AlgorithmCategory.SIGN,
+        'PURE_EDDSA': AlgorithmCategory.SIGN,
+        'RSA_PSS': AlgorithmCategory.SIGN,
+        'RSA_PKCS1V15_SIGN': AlgorithmCategory.SIGN,
+        'RSA_PKCS1V15_CRYPT': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
+        'RSA_OAEP': AlgorithmCategory.ASYMMETRIC_ENCRYPTION,
+        'HKDF': AlgorithmCategory.KEY_DERIVATION,
+        'TLS12_PRF': AlgorithmCategory.KEY_DERIVATION,
+        'TLS12_PSK_TO_MS': AlgorithmCategory.KEY_DERIVATION,
+        'PBKDF': AlgorithmCategory.KEY_DERIVATION,
+        'ECDH': AlgorithmCategory.KEY_AGREEMENT,
+        'FFDH': AlgorithmCategory.KEY_AGREEMENT,
+        # KEY_AGREEMENT(...) is a key derivation with a key agreement component
+        'KEY_AGREEMENT': AlgorithmCategory.KEY_DERIVATION,
+        'JPAKE': AlgorithmCategory.PAKE,
+    }
+    for x in BLOCK_MAC_MODES:
+        CATEGORY_FROM_HEAD[x] = AlgorithmCategory.MAC
+    for x in BLOCK_CIPHER_MODES:
+        CATEGORY_FROM_HEAD[x] = AlgorithmCategory.CIPHER
+    for x in BLOCK_AEAD_MODES:
+        CATEGORY_FROM_HEAD[x] = AlgorithmCategory.AEAD
+
+    def determine_category(self, expr: str, head: str) -> AlgorithmCategory:
+        """Return the category of the given algorithm expression.
+
+        This function does not attempt to detect invalid inputs.
+        """
+        prefix = head
+        while prefix:
+            if prefix in self.CATEGORY_FROM_HEAD:
+                return self.CATEGORY_FROM_HEAD[prefix]
+            if re.match(r'.*[0-9]\Z', prefix):
+                prefix = re.sub(r'_*[0-9]+\Z', r'', prefix)
+            else:
+                prefix = re.sub(r'_*[^_]*\Z', r'', prefix)
+        raise AlgorithmNotRecognized(expr)
+
+    @staticmethod
+    def determine_wildcard(expr) -> bool:
+        """Whether the given algorithm expression is a wildcard.
+
+        This function does not attempt to detect invalid inputs.
+        """
+        if re.search(r'\bPSA_ALG_ANY_HASH\b', expr):
+            return True
+        if re.search(r'_AT_LEAST_', expr):
+            return True
+        return False
+
+    def __init__(self, expr: str) -> None:
+        """Analyze an algorithm value.
+
+        The algorithm must be expressed as a C expression containing only
+        calls to PSA algorithm constructor macros and numeric literals.
+
+        This class is only programmed to handle valid expressions. Invalid
+        expressions may result in exceptions or in nonsensical results.
+        """
+        self.expression = re.sub(r'\s+', r'', expr)
+        self.base_expression = self.determine_base(self.expression)
+        self.head = self.determine_head(self.base_expression)
+        self.category = self.determine_category(self.base_expression, self.head)
+        self.is_wildcard = self.determine_wildcard(self.expression)
+
+    def is_key_agreement_with_derivation(self) -> bool:
+        """Whether this is a combined key agreement and key derivation algorithm."""
+        if self.category != AlgorithmCategory.KEY_AGREEMENT:
+            return False
+        m = re.match(r'PSA_ALG_KEY_AGREEMENT\(\w+,\s*(.*)\)\Z', self.expression)
+        if not m:
+            return False
+        kdf_alg = m.group(1)
+        # Assume kdf_alg is either a valid KDF or 0.
+        return not re.match(r'(?:0[Xx])?0+\s*\Z', kdf_alg)
+
+    def can_do(self, category: AlgorithmCategory) -> bool:
+        """Whether this algorithm fits the specified operation category."""
+        if category == self.category:
+            return True
+        if category == AlgorithmCategory.KEY_DERIVATION and \
+           self.is_key_agreement_with_derivation():
+            return True
+        return False
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 2431e40..6049b74 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -46,16 +46,26 @@
             --directory ${CMAKE_CURRENT_BINARY_DIR}/suites
         DEPENDS
             ${CMAKE_CURRENT_SOURCE_DIR}/../tests/scripts/generate_psa_tests.py
+            ${CMAKE_CURRENT_SOURCE_DIR}/../scripts/mbedtls_dev/crypto_knowledge.py
+            ${CMAKE_CURRENT_SOURCE_DIR}/../scripts/mbedtls_dev/macro_collector.py
+            ${CMAKE_CURRENT_SOURCE_DIR}/../scripts/mbedtls_dev/psa_storage.py
+            ${CMAKE_CURRENT_SOURCE_DIR}/../scripts/mbedtls_dev/test_case.py
             ${CMAKE_CURRENT_SOURCE_DIR}/../include/psa/crypto_config.h
             ${CMAKE_CURRENT_SOURCE_DIR}/../include/psa/crypto_values.h
             ${CMAKE_CURRENT_SOURCE_DIR}/../include/psa/crypto_extra.h
     )
+
 else()
     foreach(file ${base_generated_data_files})
         link_to_source(${file})
     endforeach()
 endif()
-
+# CMake generates sub-makefiles for each target and calls them in subprocesses.
+# Without this command, cmake will generate rules in each sub-makefile. As a result,
+# they can cause race conditions in parallel builds.
+# With this line, only 4 sub-makefiles include the above command, that reduces
+# the risk of a race.
+add_custom_target(test_suite_generated_data DEPENDS ${generated_data_files})
 # Test suites caught by SKIP_TEST_SUITES are built but not executed.
 # "foo" as a skip pattern skips "test_suite_foo" and "test_suite_foo.bar"
 # but not "test_suite_foobar".
@@ -119,6 +129,7 @@
     )
 
     add_executable(test_suite_${data_name} test_suite_${data_name}.c $<TARGET_OBJECTS:mbedtls_test>)
+    add_dependencies(test_suite_${data_name} test_suite_generated_data)
     target_link_libraries(test_suite_${data_name} ${libs})
     # Include test-specific header files from ./include and private header
     # files (used by some invasive tests) from ../library. Public header
diff --git a/tests/Makefile b/tests/Makefile
index 94a834e..0d08f84 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -84,6 +84,10 @@
 .SECONDARY: generated_psa_test_data
 $(GENERATED_DATA_FILES): generated_psa_test_data
 generated_psa_test_data: scripts/generate_psa_tests.py
+generated_psa_test_data: ../scripts/mbedtls_dev/crypto_knowledge.py
+generated_psa_test_data: ../scripts/mbedtls_dev/macro_collector.py
+generated_psa_test_data: ../scripts/mbedtls_dev/psa_storage.py
+generated_psa_test_data: ../scripts/mbedtls_dev/test_case.py
 ## The generated file only depends on the options that are present in
 ## crypto_config.h, not on which options are set. To avoid regenerating this
 ## file all the time when switching between configurations, don't declare
diff --git a/tests/compat.sh b/tests/compat.sh
index c8a883d..d681217 100755
--- a/tests/compat.sh
+++ b/tests/compat.sh
@@ -67,17 +67,18 @@
 fi
 
 # default values for options
+# /!\ keep this synchronised with:
+# - basic-build-test.sh
+# - all.sh (multiple components)
 MODES="tls12 dtls12"
 VERIFIES="NO YES"
 TYPES="ECDSA RSA PSK"
 FILTER=""
-# exclude:
-# - NULL: excluded from our default config
-#   avoid plain DES but keep 3DES-EDE-CBC (mbedTLS), DES-CBC3 (OpenSSL)
-# - ARIA: not in default mbedtls_config.h + requires OpenSSL >= 1.1.1
+# By default, exclude:
+# - NULL: excluded from our default config + requires OpenSSL legacy
+# - ARIA: requires OpenSSL >= 1.1.1
 # - ChachaPoly: requires OpenSSL >= 1.1.0
-# - 3DES: not in default config
-EXCLUDE='NULL\|DES\|ARIA\|CHACHA20-POLY1305'
+EXCLUDE='NULL\|ARIA\|CHACHA20-POLY1305'
 VERBOSE=""
 MEMCHECK=0
 PEERS="OpenSSL$PEER_GNUTLS mbedTLS"
@@ -245,73 +246,50 @@
     case $TYPE in
 
         "ECDSA")
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDHE-ECDSA-WITH-NULL-SHA           \
-                    TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA   \
-                    TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA    \
-                    TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA    \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                                   \
-                    TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256         \
-                    TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384         \
-                    TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256         \
-                    TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384         \
-                    "
-            fi
+            CIPHERS="$CIPHERS                           \
+                TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA    \
+                TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256 \
+                TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256 \
+                TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA    \
+                TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384 \
+                TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384 \
+                TLS-ECDHE-ECDSA-WITH-NULL-SHA           \
+                "
             ;;
 
         "RSA")
             CIPHERS="$CIPHERS                           \
                 TLS-DHE-RSA-WITH-AES-128-CBC-SHA        \
+                TLS-DHE-RSA-WITH-AES-128-CBC-SHA256     \
+                TLS-DHE-RSA-WITH-AES-128-GCM-SHA256     \
                 TLS-DHE-RSA-WITH-AES-256-CBC-SHA        \
+                TLS-DHE-RSA-WITH-AES-256-CBC-SHA256     \
+                TLS-DHE-RSA-WITH-AES-256-GCM-SHA384     \
                 TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA   \
                 TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA   \
-                TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA       \
-                TLS-RSA-WITH-AES-256-CBC-SHA            \
-                TLS-RSA-WITH-CAMELLIA-256-CBC-SHA       \
+                TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA      \
+                TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256   \
+                TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256   \
+                TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA      \
+                TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384   \
+                TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384   \
+                TLS-ECDHE-RSA-WITH-NULL-SHA             \
                 TLS-RSA-WITH-AES-128-CBC-SHA            \
+                TLS-RSA-WITH-AES-128-CBC-SHA256         \
+                TLS-RSA-WITH-AES-128-GCM-SHA256         \
+                TLS-RSA-WITH-AES-256-CBC-SHA            \
+                TLS-RSA-WITH-AES-256-CBC-SHA256         \
+                TLS-RSA-WITH-AES-256-GCM-SHA384         \
                 TLS-RSA-WITH-CAMELLIA-128-CBC-SHA       \
-                TLS-RSA-WITH-3DES-EDE-CBC-SHA           \
+                TLS-RSA-WITH-CAMELLIA-256-CBC-SHA       \
                 TLS-RSA-WITH-NULL-MD5                   \
                 TLS-RSA-WITH-NULL-SHA                   \
+                TLS-RSA-WITH-NULL-SHA256                \
                 "
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA      \
-                    TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA      \
-                    TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA     \
-                    TLS-ECDHE-RSA-WITH-NULL-SHA             \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-RSA-WITH-AES-128-CBC-SHA256         \
-                    TLS-DHE-RSA-WITH-AES-128-CBC-SHA256     \
-                    TLS-RSA-WITH-AES-256-CBC-SHA256         \
-                    TLS-DHE-RSA-WITH-AES-256-CBC-SHA256     \
-                    TLS-ECDHE-RSA-WITH-AES-128-CBC-SHA256   \
-                    TLS-ECDHE-RSA-WITH-AES-256-CBC-SHA384   \
-                    TLS-RSA-WITH-AES-128-GCM-SHA256         \
-                    TLS-RSA-WITH-AES-256-GCM-SHA384         \
-                    TLS-DHE-RSA-WITH-AES-128-GCM-SHA256     \
-                    TLS-DHE-RSA-WITH-AES-256-GCM-SHA384     \
-                    TLS-ECDHE-RSA-WITH-AES-128-GCM-SHA256   \
-                    TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384   \
-                    TLS-RSA-WITH-NULL-SHA256                \
-                    "
-            fi
             ;;
 
         "PSK")
             CIPHERS="$CIPHERS                           \
-                TLS-PSK-WITH-3DES-EDE-CBC-SHA           \
                 TLS-PSK-WITH-AES-128-CBC-SHA            \
                 TLS-PSK-WITH-AES-256-CBC-SHA            \
                 "
@@ -347,62 +325,43 @@
     case $TYPE in
 
         "ECDSA")
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDH-ECDSA-WITH-NULL-SHA       \
-                    TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA    \
-                    TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA     \
-                    TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA     \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256     \
-                    TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384          \
-                    TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256          \
-                    TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384          \
-                    TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384        \
-                    TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256        \
-                    TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256   \
-                    "
-            fi
+            CIPHERS="$CIPHERS                                   \
+                TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA             \
+                TLS-ECDH-ECDSA-WITH-AES-128-CBC-SHA256          \
+                TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256          \
+                TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA             \
+                TLS-ECDH-ECDSA-WITH-AES-256-CBC-SHA384          \
+                TLS-ECDH-ECDSA-WITH-AES-256-GCM-SHA384          \
+                TLS-ECDH-ECDSA-WITH-NULL-SHA                    \
+                TLS-ECDHE-ECDSA-WITH-ARIA-128-GCM-SHA256        \
+                TLS-ECDHE-ECDSA-WITH-ARIA-256-GCM-SHA384        \
+                TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256   \
+                "
             ;;
 
         "RSA")
-            CIPHERS="$CIPHERS                           \
-                TLS-RSA-WITH-DES-CBC-SHA           \
-                TLS-DHE-RSA-WITH-DES-CBC-SHA            \
+            CIPHERS="$CIPHERS                                   \
+                TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256            \
+                TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384            \
+                TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256       \
+                TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256          \
+                TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384          \
+                TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256     \
+                TLS-RSA-WITH-ARIA-128-GCM-SHA256                \
+                TLS-RSA-WITH-ARIA-256-GCM-SHA384                \
                 "
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDHE-RSA-WITH-ARIA-256-GCM-SHA384     \
-                    TLS-DHE-RSA-WITH-ARIA-256-GCM-SHA384            \
-                    TLS-RSA-WITH-ARIA-256-GCM-SHA384                \
-                    TLS-ECDHE-RSA-WITH-ARIA-128-GCM-SHA256          \
-                    TLS-DHE-RSA-WITH-ARIA-128-GCM-SHA256            \
-                    TLS-RSA-WITH-ARIA-128-GCM-SHA256                \
-                    TLS-DHE-RSA-WITH-CHACHA20-POLY1305-SHA256       \
-                    TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256     \
-                    "
-            fi
             ;;
 
         "PSK")
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384       \
-                    TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256            \
-                    TLS-PSK-WITH-ARIA-256-GCM-SHA384                \
-                    TLS-PSK-WITH-ARIA-128-GCM-SHA256                \
-                    TLS-PSK-WITH-CHACHA20-POLY1305-SHA256           \
-                    TLS-ECDHE-PSK-WITH-CHACHA20-POLY1305-SHA256     \
-                    TLS-DHE-PSK-WITH-CHACHA20-POLY1305-SHA256       \
-                    "
-            fi
+            CIPHERS="$CIPHERS                                   \
+                TLS-DHE-PSK-WITH-ARIA-128-GCM-SHA256            \
+                TLS-DHE-PSK-WITH-ARIA-256-GCM-SHA384            \
+                TLS-DHE-PSK-WITH-CHACHA20-POLY1305-SHA256       \
+                TLS-ECDHE-PSK-WITH-CHACHA20-POLY1305-SHA256     \
+                TLS-PSK-WITH-ARIA-128-GCM-SHA256                \
+                TLS-PSK-WITH-ARIA-256-GCM-SHA384                \
+                TLS-PSK-WITH-CHACHA20-POLY1305-SHA256           \
+                "
             ;;
     esac
 
@@ -424,115 +383,96 @@
     case $TYPE in
 
         "ECDSA")
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                           \
-                    TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256   \
-                    TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384        \
-                    TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256        \
-                    TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384        \
-                    TLS-ECDHE-ECDSA-WITH-AES-128-CCM                    \
-                    TLS-ECDHE-ECDSA-WITH-AES-256-CCM                    \
-                    TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8                  \
-                    TLS-ECDHE-ECDSA-WITH-AES-256-CCM-8                  \
-                   "
-            fi
+            CIPHERS="$CIPHERS                                       \
+                TLS-ECDHE-ECDSA-WITH-AES-128-CCM                    \
+                TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8                  \
+                TLS-ECDHE-ECDSA-WITH-AES-256-CCM                    \
+                TLS-ECDHE-ECDSA-WITH-AES-256-CCM-8                  \
+                TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-CBC-SHA256        \
+                TLS-ECDHE-ECDSA-WITH-CAMELLIA-128-GCM-SHA256        \
+                TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-CBC-SHA384        \
+                TLS-ECDHE-ECDSA-WITH-CAMELLIA-256-GCM-SHA384        \
+                "
             ;;
 
         "RSA")
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                               \
-                    TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256  \
-                    TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384  \
-                    TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256        \
-                    TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256        \
-                    TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256    \
-                    TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256    \
-                    TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256  \
-                    TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384  \
-                    TLS-DHE-RSA-WITH-CAMELLIA-128-GCM-SHA256    \
-                    TLS-DHE-RSA-WITH-CAMELLIA-256-GCM-SHA384    \
-                    TLS-RSA-WITH-CAMELLIA-128-GCM-SHA256        \
-                    TLS-RSA-WITH-CAMELLIA-256-GCM-SHA384        \
-                    TLS-RSA-WITH-AES-128-CCM                    \
-                    TLS-RSA-WITH-AES-256-CCM                    \
-                    TLS-DHE-RSA-WITH-AES-128-CCM                \
-                    TLS-DHE-RSA-WITH-AES-256-CCM                \
-                    TLS-RSA-WITH-AES-128-CCM-8                  \
-                    TLS-RSA-WITH-AES-256-CCM-8                  \
-                    TLS-DHE-RSA-WITH-AES-128-CCM-8              \
-                    TLS-DHE-RSA-WITH-AES-256-CCM-8              \
-                    "
-            fi
+            CIPHERS="$CIPHERS                               \
+                TLS-DHE-RSA-WITH-AES-128-CCM                \
+                TLS-DHE-RSA-WITH-AES-128-CCM-8              \
+                TLS-DHE-RSA-WITH-AES-256-CCM                \
+                TLS-DHE-RSA-WITH-AES-256-CCM-8              \
+                TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256    \
+                TLS-DHE-RSA-WITH-CAMELLIA-128-GCM-SHA256    \
+                TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256    \
+                TLS-DHE-RSA-WITH-CAMELLIA-256-GCM-SHA384    \
+                TLS-ECDHE-RSA-WITH-CAMELLIA-128-CBC-SHA256  \
+                TLS-ECDHE-RSA-WITH-CAMELLIA-128-GCM-SHA256  \
+                TLS-ECDHE-RSA-WITH-CAMELLIA-256-CBC-SHA384  \
+                TLS-ECDHE-RSA-WITH-CAMELLIA-256-GCM-SHA384  \
+                TLS-RSA-WITH-AES-128-CCM                    \
+                TLS-RSA-WITH-AES-128-CCM-8                  \
+                TLS-RSA-WITH-AES-256-CCM                    \
+                TLS-RSA-WITH-AES-256-CCM-8                  \
+                TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256        \
+                TLS-RSA-WITH-CAMELLIA-128-GCM-SHA256        \
+                TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256        \
+                TLS-RSA-WITH-CAMELLIA-256-GCM-SHA384        \
+                "
             ;;
 
         "PSK")
-            CIPHERS="$CIPHERS                                 \
-                TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA             \
-                TLS-DHE-PSK-WITH-AES-128-CBC-SHA              \
-                TLS-DHE-PSK-WITH-AES-256-CBC-SHA              \
+            CIPHERS="$CIPHERS                               \
+                TLS-DHE-PSK-WITH-AES-128-CBC-SHA            \
+                TLS-DHE-PSK-WITH-AES-128-CBC-SHA256         \
+                TLS-DHE-PSK-WITH-AES-128-CCM                \
+                TLS-DHE-PSK-WITH-AES-128-CCM-8              \
+                TLS-DHE-PSK-WITH-AES-128-GCM-SHA256         \
+                TLS-DHE-PSK-WITH-AES-256-CBC-SHA            \
+                TLS-DHE-PSK-WITH-AES-256-CBC-SHA384         \
+                TLS-DHE-PSK-WITH-AES-256-CCM                \
+                TLS-DHE-PSK-WITH-AES-256-CCM-8              \
+                TLS-DHE-PSK-WITH-AES-256-GCM-SHA384         \
+                TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256    \
+                TLS-DHE-PSK-WITH-CAMELLIA-128-GCM-SHA256    \
+                TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384    \
+                TLS-DHE-PSK-WITH-CAMELLIA-256-GCM-SHA384    \
+                TLS-DHE-PSK-WITH-NULL-SHA256                \
+                TLS-DHE-PSK-WITH-NULL-SHA384                \
+                TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA          \
+                TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256       \
+                TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA          \
+                TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA384       \
+                TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256  \
+                TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384  \
+                TLS-ECDHE-PSK-WITH-NULL-SHA256              \
+                TLS-ECDHE-PSK-WITH-NULL-SHA384              \
+                TLS-PSK-WITH-AES-128-CBC-SHA256             \
+                TLS-PSK-WITH-AES-128-CCM                    \
+                TLS-PSK-WITH-AES-128-CCM-8                  \
+                TLS-PSK-WITH-AES-128-GCM-SHA256             \
+                TLS-PSK-WITH-AES-256-CBC-SHA384             \
+                TLS-PSK-WITH-AES-256-CCM                    \
+                TLS-PSK-WITH-AES-256-CCM-8                  \
+                TLS-PSK-WITH-AES-256-GCM-SHA384             \
+                TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256        \
+                TLS-PSK-WITH-CAMELLIA-128-GCM-SHA256        \
+                TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384        \
+                TLS-PSK-WITH-CAMELLIA-256-GCM-SHA384        \
+                TLS-PSK-WITH-NULL-SHA256                    \
+                TLS-PSK-WITH-NULL-SHA384                    \
+                TLS-RSA-PSK-WITH-AES-128-CBC-SHA            \
+                TLS-RSA-PSK-WITH-AES-128-CBC-SHA256         \
+                TLS-RSA-PSK-WITH-AES-128-GCM-SHA256         \
+                TLS-RSA-PSK-WITH-AES-256-CBC-SHA            \
+                TLS-RSA-PSK-WITH-AES-256-CBC-SHA384         \
+                TLS-RSA-PSK-WITH-AES-256-GCM-SHA384         \
+                TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256    \
+                TLS-RSA-PSK-WITH-CAMELLIA-128-GCM-SHA256    \
+                TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384    \
+                TLS-RSA-PSK-WITH-CAMELLIA-256-GCM-SHA384    \
+                TLS-RSA-PSK-WITH-NULL-SHA256                \
+                TLS-RSA-PSK-WITH-NULL-SHA384                \
                 "
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                CIPHERS="$CIPHERS                               \
-                    TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA          \
-                    TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA          \
-                    TLS-ECDHE-PSK-WITH-3DES-EDE-CBC-SHA         \
-                    TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA           \
-                    TLS-RSA-PSK-WITH-AES-256-CBC-SHA            \
-                    TLS-RSA-PSK-WITH-AES-128-CBC-SHA            \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                CIPHERS="$CIPHERS                               \
-                    TLS-ECDHE-PSK-WITH-AES-256-CBC-SHA384       \
-                    TLS-ECDHE-PSK-WITH-CAMELLIA-256-CBC-SHA384  \
-                    TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256       \
-                    TLS-ECDHE-PSK-WITH-CAMELLIA-128-CBC-SHA256  \
-                    TLS-ECDHE-PSK-WITH-NULL-SHA384              \
-                    TLS-ECDHE-PSK-WITH-NULL-SHA256              \
-                    TLS-PSK-WITH-AES-128-CBC-SHA256             \
-                    TLS-PSK-WITH-AES-256-CBC-SHA384             \
-                    TLS-DHE-PSK-WITH-AES-128-CBC-SHA256         \
-                    TLS-DHE-PSK-WITH-AES-256-CBC-SHA384         \
-                    TLS-PSK-WITH-NULL-SHA256                    \
-                    TLS-PSK-WITH-NULL-SHA384                    \
-                    TLS-DHE-PSK-WITH-NULL-SHA256                \
-                    TLS-DHE-PSK-WITH-NULL-SHA384                \
-                    TLS-RSA-PSK-WITH-AES-256-CBC-SHA384         \
-                    TLS-RSA-PSK-WITH-AES-128-CBC-SHA256         \
-                    TLS-RSA-PSK-WITH-NULL-SHA256                \
-                    TLS-RSA-PSK-WITH-NULL-SHA384                \
-                    TLS-DHE-PSK-WITH-CAMELLIA-128-CBC-SHA256    \
-                    TLS-DHE-PSK-WITH-CAMELLIA-256-CBC-SHA384    \
-                    TLS-PSK-WITH-CAMELLIA-128-CBC-SHA256        \
-                    TLS-PSK-WITH-CAMELLIA-256-CBC-SHA384        \
-                    TLS-RSA-PSK-WITH-CAMELLIA-256-CBC-SHA384    \
-                    TLS-RSA-PSK-WITH-CAMELLIA-128-CBC-SHA256    \
-                    TLS-PSK-WITH-AES-128-GCM-SHA256             \
-                    TLS-PSK-WITH-AES-256-GCM-SHA384             \
-                    TLS-DHE-PSK-WITH-AES-128-GCM-SHA256         \
-                    TLS-DHE-PSK-WITH-AES-256-GCM-SHA384         \
-                    TLS-PSK-WITH-AES-128-CCM                    \
-                    TLS-PSK-WITH-AES-256-CCM                    \
-                    TLS-DHE-PSK-WITH-AES-128-CCM                \
-                    TLS-DHE-PSK-WITH-AES-256-CCM                \
-                    TLS-PSK-WITH-AES-128-CCM-8                  \
-                    TLS-PSK-WITH-AES-256-CCM-8                  \
-                    TLS-DHE-PSK-WITH-AES-128-CCM-8              \
-                    TLS-DHE-PSK-WITH-AES-256-CCM-8              \
-                    TLS-RSA-PSK-WITH-CAMELLIA-128-GCM-SHA256    \
-                    TLS-RSA-PSK-WITH-CAMELLIA-256-GCM-SHA384    \
-                    TLS-PSK-WITH-CAMELLIA-128-GCM-SHA256        \
-                    TLS-PSK-WITH-CAMELLIA-256-GCM-SHA384        \
-                    TLS-DHE-PSK-WITH-CAMELLIA-128-GCM-SHA256    \
-                    TLS-DHE-PSK-WITH-CAMELLIA-256-GCM-SHA384    \
-                    TLS-RSA-PSK-WITH-AES-256-GCM-SHA384         \
-                    TLS-RSA-PSK-WITH-AES-128-GCM-SHA256         \
-                    "
-            fi
             ;;
     esac
 
@@ -551,71 +491,50 @@
     case $TYPE in
 
         "ECDSA")
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                M_CIPHERS="$M_CIPHERS                               \
-                    TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256     \
-                    TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384     \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                M_CIPHERS="$M_CIPHERS                               \
-                    TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256     \
-                    TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384     \
-                    TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384        \
-                    TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256        \
-                    TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384         \
-                    TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256         \
-                    TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384         \
-                    TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256         \
-                    "
-            fi
+            M_CIPHERS="$M_CIPHERS                               \
+                TLS-ECDH-ECDSA-WITH-ARIA-128-CBC-SHA256         \
+                TLS-ECDH-ECDSA-WITH-ARIA-128-GCM-SHA256         \
+                TLS-ECDH-ECDSA-WITH-ARIA-256-CBC-SHA384         \
+                TLS-ECDH-ECDSA-WITH-ARIA-256-GCM-SHA384         \
+                TLS-ECDH-ECDSA-WITH-CAMELLIA-128-CBC-SHA256     \
+                TLS-ECDH-ECDSA-WITH-CAMELLIA-128-GCM-SHA256     \
+                TLS-ECDH-ECDSA-WITH-CAMELLIA-256-CBC-SHA384     \
+                TLS-ECDH-ECDSA-WITH-CAMELLIA-256-GCM-SHA384     \
+                TLS-ECDHE-ECDSA-WITH-ARIA-128-CBC-SHA256        \
+                TLS-ECDHE-ECDSA-WITH-ARIA-256-CBC-SHA384        \
+                "
             ;;
 
         "RSA")
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                M_CIPHERS="$M_CIPHERS                               \
-                    TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384          \
-                    TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384            \
-                    TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256          \
-                    TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256            \
-                    TLS-RSA-WITH-ARIA-256-CBC-SHA384                \
-                    TLS-RSA-WITH-ARIA-128-CBC-SHA256                \
-                    "
-            fi
+            M_CIPHERS="$M_CIPHERS                               \
+                TLS-DHE-RSA-WITH-ARIA-128-CBC-SHA256            \
+                TLS-DHE-RSA-WITH-ARIA-256-CBC-SHA384            \
+                TLS-ECDHE-RSA-WITH-ARIA-128-CBC-SHA256          \
+                TLS-ECDHE-RSA-WITH-ARIA-256-CBC-SHA384          \
+                TLS-RSA-WITH-ARIA-128-CBC-SHA256                \
+                TLS-RSA-WITH-ARIA-256-CBC-SHA384                \
+                "
             ;;
 
         "PSK")
             # *PSK-NULL-SHA suites supported by GnuTLS 3.3.5 but not 3.2.15
-            M_CIPHERS="$M_CIPHERS                        \
-                TLS-PSK-WITH-NULL-SHA                    \
-                TLS-DHE-PSK-WITH-NULL-SHA                \
+            M_CIPHERS="$M_CIPHERS                               \
+                TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256            \
+                TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384            \
+                TLS-DHE-PSK-WITH-NULL-SHA                       \
+                TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256          \
+                TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384          \
+                TLS-ECDHE-PSK-WITH-NULL-SHA                     \
+                TLS-PSK-WITH-ARIA-128-CBC-SHA256                \
+                TLS-PSK-WITH-ARIA-256-CBC-SHA384                \
+                TLS-PSK-WITH-NULL-SHA                           \
+                TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256            \
+                TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256            \
+                TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384            \
+                TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384            \
+                TLS-RSA-PSK-WITH-CHACHA20-POLY1305-SHA256       \
+                TLS-RSA-PSK-WITH-NULL-SHA                       \
                 "
-            if [ `minor_ver "$MODE"` -gt 0 ]
-            then
-                M_CIPHERS="$M_CIPHERS                    \
-                    TLS-ECDHE-PSK-WITH-NULL-SHA          \
-                    TLS-RSA-PSK-WITH-NULL-SHA            \
-                    "
-            fi
-            if [ `minor_ver "$MODE"` -ge 3 ]
-            then
-                M_CIPHERS="$M_CIPHERS                               \
-                    TLS-RSA-PSK-WITH-ARIA-256-CBC-SHA384            \
-                    TLS-RSA-PSK-WITH-ARIA-128-CBC-SHA256            \
-                    TLS-PSK-WITH-ARIA-256-CBC-SHA384                \
-                    TLS-PSK-WITH-ARIA-128-CBC-SHA256                \
-                    TLS-RSA-PSK-WITH-ARIA-256-GCM-SHA384            \
-                    TLS-RSA-PSK-WITH-ARIA-128-GCM-SHA256            \
-                    TLS-ECDHE-PSK-WITH-ARIA-256-CBC-SHA384          \
-                    TLS-ECDHE-PSK-WITH-ARIA-128-CBC-SHA256          \
-                    TLS-DHE-PSK-WITH-ARIA-256-CBC-SHA384            \
-                    TLS-DHE-PSK-WITH-ARIA-128-CBC-SHA256            \
-                    TLS-RSA-PSK-WITH-CHACHA20-POLY1305-SHA256       \
-                    "
-            fi
             ;;
     esac
 }
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index 07e708b..55806fd 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -1226,7 +1226,7 @@
 
     msg "test: Everest ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min
     # Exclude some symmetric ciphers that are redundant here to gain time.
-    tests/compat.sh -f ECDH -V NO -e 'ARIA\|CAMELLIA\|CHACHA\|DES'
+    tests/compat.sh -f ECDH -V NO -e 'ARIA\|CAMELLIA\|CHACHA'
 }
 
 component_test_everest_curve25519_only () {
@@ -1314,8 +1314,8 @@
     msg "test: ssl-opt.sh default, ECJPAKE, SSL async (full config)" # ~ 1s
     tests/ssl-opt.sh -f 'Default\|ECJPAKE\|SSL async private'
 
-    msg "test: compat.sh DES, 3DES & NULL (full config)" # ~ 2 min
-    env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '^$' -f 'NULL\|DES'
+    msg "test: compat.sh NULL (full config)" # ~ 2 min
+    env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '^$' -f 'NULL'
 
     msg "test: compat.sh ARIA + ChachaPoly"
     env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
@@ -1607,8 +1607,8 @@
     msg "test: compat.sh default (full minus MBEDTLS_USE_PSA_CRYPTO)"
     tests/compat.sh
 
-    msg "test: compat.sh DES & NULL (full minus MBEDTLS_USE_PSA_CRYPTO)"
-    env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '3DES\|DES-CBC3' -f 'NULL\|DES'
+    msg "test: compat.sh NULL (full minus MBEDTLS_USE_PSA_CRYPTO)"
+    env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -f 'NULL'
 
     msg "test: compat.sh ARIA + ChachaPoly (full minus MBEDTLS_USE_PSA_CRYPTO)"
     env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
@@ -2600,7 +2600,7 @@
 
     msg "test: i386, Everest ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min
     # Exclude some symmetric ciphers that are redundant here to gain time.
-    tests/compat.sh -f ECDH -V NO -e 'ARIA\|CAMELLIA\|CHACHA\|DES'
+    tests/compat.sh -f ECDH -V NO -e 'ARIA\|CAMELLIA\|CHACHA'
 }
 support_test_m32_everest () {
     support_test_m32_o0 "$@"
diff --git a/tests/scripts/basic-build-test.sh b/tests/scripts/basic-build-test.sh
index cf68b4e..31beb1c 100755
--- a/tests/scripts/basic-build-test.sh
+++ b/tests/scripts/basic-build-test.sh
@@ -121,13 +121,13 @@
 echo '################ compat.sh ################'
 {
     echo '#### compat.sh: Default versions'
-    sh compat.sh -m 'tls1_2 dtls1_2'
+    sh compat.sh
     echo
 
-    echo '#### compat.sh: legacy (null, DES)'
+    echo '#### compat.sh: legacy (null)'
     OPENSSL_CMD="$OPENSSL_LEGACY" \
     GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" \
-    sh compat.sh -e '^$' -f 'NULL\|DES'
+    sh compat.sh -e '^$' -f 'NULL'
     echo
 
     echo '#### compat.sh: next (ARIA, ChaCha)'
diff --git a/tests/scripts/check-generated-files.sh b/tests/scripts/check-generated-files.sh
index f42ecd6..1736f24 100755
--- a/tests/scripts/check-generated-files.sh
+++ b/tests/scripts/check-generated-files.sh
@@ -76,7 +76,7 @@
 
     for FILE in "$@"; do
         if [ -e "$FILE" ]; then
-            cp "$FILE" "$FILE.bak"
+            cp -p "$FILE" "$FILE.bak"
         else
             rm -f "$FILE.bak"
         fi
@@ -86,17 +86,18 @@
 
     # Compare the script output to the old files and remove backups
     for FILE in "$@"; do
-        if ! diff "$FILE" "$FILE.bak" >/dev/null 2>&1; then
+        if diff "$FILE" "$FILE.bak" >/dev/null 2>&1; then
+            # Move the original file back so that $FILE's timestamp doesn't
+            # change (avoids spurious rebuilds with make).
+            mv "$FILE.bak" "$FILE"
+        else
             echo "'$FILE' was either modified or deleted by '$SCRIPT'"
             if [ -z "$UPDATE" ]; then
                 exit 1
+            else
+                rm -f "$FILE.bak"
             fi
         fi
-        if [ -z "$UPDATE" ]; then
-            mv "$FILE.bak" "$FILE"
-        else
-            rm -f "$FILE.bak"
-        fi
     done
 
     if [ -n "$directory" ]; then
diff --git a/tests/scripts/generate_psa_tests.py b/tests/scripts/generate_psa_tests.py
index 75ef353..ca94d7d 100755
--- a/tests/scripts/generate_psa_tests.py
+++ b/tests/scripts/generate_psa_tests.py
@@ -21,6 +21,7 @@
 # limitations under the License.
 
 import argparse
+import enum
 import os
 import posixpath
 import re
@@ -305,6 +306,145 @@
                 kt = crypto_knowledge.KeyType(constr, [curve_family])
                 yield from self.test_cases_for_key_type_key_generation(kt)
 
+class OpFail:
+    """Generate test cases for operations that must fail."""
+    #pylint: disable=too-few-public-methods
+
+    class Reason(enum.Enum):
+        NOT_SUPPORTED = 0
+        INVALID = 1
+        INCOMPATIBLE = 2
+        PUBLIC = 3
+
+    def __init__(self, info: Information) -> None:
+        self.constructors = info.constructors
+        key_type_expressions = self.constructors.generate_expressions(
+            sorted(self.constructors.key_types)
+        )
+        self.key_types = [crypto_knowledge.KeyType(kt_expr)
+                          for kt_expr in key_type_expressions]
+
+    def make_test_case(
+            self,
+            alg: crypto_knowledge.Algorithm,
+            category: crypto_knowledge.AlgorithmCategory,
+            reason: 'Reason',
+            kt: Optional[crypto_knowledge.KeyType] = None,
+            not_deps: FrozenSet[str] = frozenset(),
+    ) -> test_case.TestCase:
+        """Construct a failure test case for a one-key or keyless operation."""
+        #pylint: disable=too-many-arguments,too-many-locals
+        tc = test_case.TestCase()
+        pretty_alg = re.sub(r'PSA_ALG_', r'', alg.expression)
+        if reason == self.Reason.NOT_SUPPORTED:
+            short_deps = [re.sub(r'PSA_WANT_ALG_', r'', dep)
+                          for dep in not_deps]
+            pretty_reason = '!' + '&'.join(sorted(short_deps))
+        else:
+            pretty_reason = reason.name.lower()
+        if kt:
+            key_type = kt.expression
+            pretty_type = re.sub(r'PSA_KEY_TYPE_', r'', key_type)
+        else:
+            key_type = ''
+            pretty_type = ''
+        tc.set_description('PSA {} {}: {}{}'
+                           .format(category.name.lower(),
+                                   pretty_alg,
+                                   pretty_reason,
+                                   ' with ' + pretty_type if pretty_type else ''))
+        dependencies = automatic_dependencies(alg.base_expression, key_type)
+        for i, dep in enumerate(dependencies):
+            if dep in not_deps:
+                dependencies[i] = '!' + dep
+        tc.set_dependencies(dependencies)
+        tc.set_function(category.name.lower() + '_fail')
+        arguments = []
+        if kt:
+            key_material = kt.key_material(kt.sizes_to_test()[0])
+            arguments += [key_type, test_case.hex_string(key_material)]
+        arguments.append(alg.expression)
+        if category.is_asymmetric():
+            arguments.append('1' if reason == self.Reason.PUBLIC else '0')
+        error = ('NOT_SUPPORTED' if reason == self.Reason.NOT_SUPPORTED else
+                 'INVALID_ARGUMENT')
+        arguments.append('PSA_ERROR_' + error)
+        tc.set_arguments(arguments)
+        return tc
+
+    def no_key_test_cases(
+            self,
+            alg: crypto_knowledge.Algorithm,
+            category: crypto_knowledge.AlgorithmCategory,
+    ) -> Iterator[test_case.TestCase]:
+        """Generate failure test cases for keyless operations with the specified algorithm."""
+        if alg.can_do(category):
+            # Compatible operation, unsupported algorithm
+            for dep in automatic_dependencies(alg.base_expression):
+                yield self.make_test_case(alg, category,
+                                          self.Reason.NOT_SUPPORTED,
+                                          not_deps=frozenset([dep]))
+        else:
+            # Incompatible operation, supported algorithm
+            yield self.make_test_case(alg, category, self.Reason.INVALID)
+
+    def one_key_test_cases(
+            self,
+            alg: crypto_knowledge.Algorithm,
+            category: crypto_knowledge.AlgorithmCategory,
+    ) -> Iterator[test_case.TestCase]:
+        """Generate failure test cases for one-key operations with the specified algorithm."""
+        for kt in self.key_types:
+            key_is_compatible = kt.can_do(alg)
+            if key_is_compatible and alg.can_do(category):
+                # Compatible key and operation, unsupported algorithm
+                for dep in automatic_dependencies(alg.base_expression):
+                    yield self.make_test_case(alg, category,
+                                              self.Reason.NOT_SUPPORTED,
+                                              kt=kt, not_deps=frozenset([dep]))
+                # Public key for a private-key operation
+                if category.is_asymmetric() and kt.is_public():
+                    yield self.make_test_case(alg, category,
+                                              self.Reason.PUBLIC,
+                                              kt=kt)
+            elif key_is_compatible:
+                # Compatible key, incompatible operation, supported algorithm
+                yield self.make_test_case(alg, category,
+                                          self.Reason.INVALID,
+                                          kt=kt)
+            elif alg.can_do(category):
+                # Incompatible key, compatible operation, supported algorithm
+                yield self.make_test_case(alg, category,
+                                          self.Reason.INCOMPATIBLE,
+                                          kt=kt)
+            else:
+                # Incompatible key and operation. Don't test cases where
+                # multiple things are wrong, to keep the number of test
+                # cases reasonable.
+                pass
+
+    def test_cases_for_algorithm(
+            self,
+            alg: crypto_knowledge.Algorithm,
+    ) -> Iterator[test_case.TestCase]:
+        """Generate operation failure test cases for the specified algorithm."""
+        for category in crypto_knowledge.AlgorithmCategory:
+            if category == crypto_knowledge.AlgorithmCategory.PAKE:
+                # PAKE operations are not implemented yet
+                pass
+            elif category.requires_key():
+                yield from self.one_key_test_cases(alg, category)
+            else:
+                yield from self.no_key_test_cases(alg, category)
+
+    def all_test_cases(self) -> Iterator[test_case.TestCase]:
+        """Generate all test cases for operations that must fail."""
+        algorithms = sorted(self.constructors.algorithms)
+        for expr in self.constructors.generate_expressions(algorithms):
+            alg = crypto_knowledge.Algorithm(expr)
+            yield from self.test_cases_for_algorithm(alg)
+
+
 class StorageKey(psa_storage.Key):
     """Representation of a key for storage format testing."""
 
@@ -443,51 +583,41 @@
                 continue
             yield self.key_for_lifetime(lifetime)
 
-    def keys_for_usage_flags(
+    def key_for_usage_flags(
             self,
             usage_flags: List[str],
             short: Optional[str] = None,
-            test_implicit_usage: Optional[bool] = False
-    ) -> Iterator[StorageTestData]:
+            test_implicit_usage: Optional[bool] = True
+    ) -> StorageTestData:
         """Construct a test key for the given key usage."""
         usage = ' | '.join(usage_flags) if usage_flags else '0'
         if short is None:
             short = re.sub(r'\bPSA_KEY_USAGE_', r'', usage)
-        extra_desc = ' with implication' if test_implicit_usage else ''
+        extra_desc = ' without implication' if test_implicit_usage else ''
         description = 'usage' + extra_desc + ': ' + short
         key1 = StorageTestData(version=self.version,
                                id=1, lifetime=0x00000001,
                                type='PSA_KEY_TYPE_RAW_DATA', bits=8,
                                expected_usage=usage,
+                               without_implicit_usage=not test_implicit_usage,
                                usage=usage, alg=0, alg2=0,
                                material=b'K',
                                description=description)
-        yield key1
-
-        if test_implicit_usage:
-            description = 'usage without implication' + ': ' + short
-            key2 = StorageTestData(version=self.version,
-                                   id=1, lifetime=0x00000001,
-                                   type='PSA_KEY_TYPE_RAW_DATA', bits=8,
-                                   without_implicit_usage=True,
-                                   usage=usage, alg=0, alg2=0,
-                                   material=b'K',
-                                   description=description)
-            yield key2
+        return key1
 
     def generate_keys_for_usage_flags(self, **kwargs) -> Iterator[StorageTestData]:
         """Generate test keys covering usage flags."""
         known_flags = sorted(self.constructors.key_usage_flags)
-        yield from self.keys_for_usage_flags(['0'], **kwargs)
+        yield self.key_for_usage_flags(['0'], **kwargs)
         for usage_flag in known_flags:
-            yield from self.keys_for_usage_flags([usage_flag], **kwargs)
+            yield self.key_for_usage_flags([usage_flag], **kwargs)
         for flag1, flag2 in zip(known_flags,
                                 known_flags[1:] + [known_flags[0]]):
-            yield from self.keys_for_usage_flags([flag1, flag2], **kwargs)
+            yield self.key_for_usage_flags([flag1, flag2], **kwargs)
 
     def generate_key_for_all_usage_flags(self) -> Iterator[StorageTestData]:
         known_flags = sorted(self.constructors.key_usage_flags)
-        yield from self.keys_for_usage_flags(known_flags, short='all known')
+        yield self.key_for_usage_flags(known_flags, short='all known')
 
     def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
         yield from self.generate_keys_for_usage_flags()
@@ -593,8 +723,8 @@
 
     def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
         """Generate test keys covering usage flags."""
-        yield from self.generate_keys_for_usage_flags(test_implicit_usage=True)
-        yield from self.generate_key_for_all_usage_flags()
+        yield from super().all_keys_for_usage_flags()
+        yield from self.generate_keys_for_usage_flags(test_implicit_usage=False)
 
     def keys_for_implicit_usage(
             self,
@@ -732,6 +862,8 @@
         lambda info: KeyGenerate(info).test_cases_for_key_generation(),
         'test_suite_psa_crypto_not_supported.generated':
         lambda info: NotSupported(info).test_cases_for_not_supported(),
+        'test_suite_psa_crypto_op_fail.generated':
+        lambda info: OpFail(info).all_test_cases(),
         'test_suite_psa_crypto_storage_format.current':
         lambda info: StorageFormatForward(info, 0).all_test_cases(),
         'test_suite_psa_crypto_storage_format.v0':
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 71a3904..18fff9d 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -1164,7 +1164,8 @@
 
     analyze_test_commands "$@"
 
-    TIMES_LEFT=2
+    # One regular run and two retries
+    TIMES_LEFT=3
     while [ $TIMES_LEFT -gt 0 ]; do
         TIMES_LEFT=$(( $TIMES_LEFT - 1 ))
 
@@ -1583,6 +1584,24 @@
             -S "error" \
             -C "error"
 
+requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
+requires_config_enabled MBEDTLS_USE_PSA_CRYPTO
+requires_config_enabled MBEDTLS_X509_CRT_PARSE_C
+requires_config_enabled MBEDTLS_ECDSA_C
+requires_config_enabled MBEDTLS_SHA256_C
+run_test    "Opaque key for server authentication (ECDH-)" \
+            "$P_SRV force_version=tls12 auth_mode=required key_opaque=1\
+             crt_file=data_files/server5.ku-ka.crt\
+             key_file=data_files/server5.key" \
+            "$P_CLI" \
+            0 \
+            -c "Verifying peer X.509 certificate... ok" \
+            -c "Ciphersuite is TLS-ECDH-" \
+            -s "key types: Opaque, none" \
+            -s "Ciphersuite is TLS-ECDH-" \
+            -S "error" \
+            -C "error"
+
 # Test using an opaque private key for client/server authentication
 requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
 requires_config_enabled MBEDTLS_USE_PSA_CRYPTO
diff --git a/tests/suites/test_suite_pk.data b/tests/suites/test_suite_pk.data
index cf40e55..323efc2 100644
--- a/tests/suites/test_suite_pk.data
+++ b/tests/suites/test_suite_pk.data
@@ -41,8 +41,13 @@
 depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP521R1_ENABLED
 pk_utils:MBEDTLS_PK_ECDSA:MBEDTLS_ECP_DP_SECP521R1:521:66:"ECDSA"
 
-PK PSA utilities: setup/free, info functions, unsupported operations
-pk_psa_utils:
+PK PSA utilities: ECDSA setup/free, info functions, unsupported operations
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
+pk_psa_utils:0
+
+PK PSA utilities: RSA setup/free, info functions, unsupported operations
+depends_on:MBEDTLS_RSA_C:MBEDTLS_GENPRIME
+pk_psa_utils:1
 
 RSA verify test vector #1 (good)
 depends_on:MBEDTLS_SHA1_C:MBEDTLS_PKCS1_V15
@@ -305,41 +310,45 @@
 pk_sign_verify_restart:MBEDTLS_PK_ECKEY:MBEDTLS_ECP_DP_SECP256R1:"C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721":"60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6":"7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299":MBEDTLS_MD_SHA256:"test":"3045022100f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d383670220019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083":250:2:64
 
 PSA wrapped sign: SECP256R1
-depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_SECP256R1:PSA_ECC_FAMILY_SECP_R1:256
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_SECP256R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1):256
 
 PSA wrapped sign: SECP384R1
-depends_on:MBEDTLS_ECP_DP_SECP384R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_SECP384R1:PSA_ECC_FAMILY_SECP_R1:384
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_SECP384R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1):384
 
 PSA wrapped sign: SECP521R1
-depends_on:MBEDTLS_ECP_DP_SECP521R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_SECP521R1:PSA_ECC_FAMILY_SECP_R1:521
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP521R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_SECP521R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1):521
 
 PSA wrapped sign: SECP192K1
-depends_on:MBEDTLS_ECP_DP_SECP192K1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_SECP192K1:PSA_ECC_FAMILY_SECP_K1:192
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP192K1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_SECP192K1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_K1):192
 
 ## Currently buggy: https://github.com/ARMmbed/mbed-crypto/issues/336
 # PSA wrapped sign: SECP224K1
-# depends_on:MBEDTLS_ECP_DP_SECP224K1_ENABLED
-# pk_psa_sign:MBEDTLS_ECP_DP_SECP224K1:PSA_ECC_FAMILY_SECP_K1:224
+# depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP224K1_ENABLED
+# pk_psa_sign:MBEDTLS_ECP_DP_SECP224K1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_K1):224
 
 PSA wrapped sign: SECP256K1
-depends_on:MBEDTLS_ECP_DP_SECP256K1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_SECP256K1:PSA_ECC_FAMILY_SECP_K1:256
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256K1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_SECP256K1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_K1):256
 
 PSA wrapped sign: BP256R1
-depends_on:MBEDTLS_ECP_DP_BP256R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_BP256R1:PSA_ECC_FAMILY_BRAINPOOL_P_R1:256
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_BP256R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_BP256R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_BRAINPOOL_P_R1):256
 
 PSA wrapped sign: BP384R1
-depends_on:MBEDTLS_ECP_DP_BP384R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_BP384R1:PSA_ECC_FAMILY_BRAINPOOL_P_R1:384
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_BP384R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_BP384R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_BRAINPOOL_P_R1):384
 
 PSA wrapped sign: BP512R1
-depends_on:MBEDTLS_ECP_DP_BP512R1_ENABLED
-pk_psa_sign:MBEDTLS_ECP_DP_BP512R1:PSA_ECC_FAMILY_BRAINPOOL_P_R1:512
+depends_on:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_BP512R1_ENABLED
+pk_psa_sign:MBEDTLS_ECP_DP_BP512R1:PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_BRAINPOOL_P_R1):512
+
+PSA wrapped sign: RSA PKCS1 v1.5
+depends_on:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15:MBEDTLS_GENPRIME
+pk_psa_sign:1024:PSA_KEY_TYPE_RSA_KEY_PAIR:1024
 
 PK Sign ext:RSA2048,PK_RSA,MD_SHA256
 depends_on:MBEDTLS_PKCS1_V15:MBEDTLS_SHA256_C:MBEDTLS_RSA_C
diff --git a/tests/suites/test_suite_pk.function b/tests/suites/test_suite_pk.function
index ccb90e7..6c4f9e4 100644
--- a/tests/suites/test_suite_pk.function
+++ b/tests/suites/test_suite_pk.function
@@ -88,11 +88,11 @@
 #if defined(MBEDTLS_USE_PSA_CRYPTO)
 
 /*
- * Generate a key using PSA and return the key identifier of that key,
+ * Generate an ECC key using PSA and return the key identifier of that key,
  * or 0 if the key generation failed.
  * The key uses NIST P-256 and is usable for signing with SHA-256.
  */
-mbedtls_svc_key_id_t pk_psa_genkey( void )
+mbedtls_svc_key_id_t pk_psa_genkey_ecc( void )
 {
     mbedtls_svc_key_id_t key;
     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
@@ -109,6 +109,27 @@
 exit:
     return( key );
 }
+
+/*
+ * Generate an RSA key using PSA and return the key identifier of that key,
+ * or 0 if the key generation failed.
+ */
+mbedtls_svc_key_id_t pk_psa_genkey_rsa( void )
+{
+    mbedtls_svc_key_id_t key;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    const psa_key_type_t type = PSA_KEY_TYPE_RSA_KEY_PAIR;
+    const size_t bits = 1024;
+
+    psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
+    psa_set_key_algorithm( &attributes, PSA_ALG_RSA_PKCS1V15_SIGN_RAW );
+    psa_set_key_type( &attributes, type );
+    psa_set_key_bits( &attributes, bits );
+    PSA_ASSERT( psa_generate_key( &attributes, &key ) );
+
+exit:
+    return( key );
+}
 #endif /* MBEDTLS_USE_PSA_CRYPTO */
 /* END_HEADER */
 
@@ -117,15 +138,15 @@
  * END_DEPENDENCIES
  */
 
-/* BEGIN_CASE depends_on:MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED */
-void pk_psa_utils(  )
+/* BEGIN_CASE depends_on:MBEDTLS_USE_PSA_CRYPTO */
+void pk_psa_utils( int key_is_rsa )
 {
     mbedtls_pk_context pk, pk2;
     mbedtls_svc_key_id_t key;
     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
 
     const char * const name = "Opaque";
-    const size_t bitlen = 256; /* harcoded in genkey() */
+    size_t bitlen;
 
     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
     unsigned char b1[1], b2[1];
@@ -145,7 +166,16 @@
     mbedtls_pk_free( &pk );
     mbedtls_pk_init( &pk );
 
-    key = pk_psa_genkey();
+    if( key_is_rsa )
+    {
+        bitlen = 1024; /* harcoded in genkey() */
+        key = pk_psa_genkey_rsa();
+    }
+    else
+    {
+        bitlen = 256; /* harcoded in genkey() */
+        key = pk_psa_genkey_ecc();
+    }
     if( mbedtls_svc_key_id_is_null( key ) )
         goto exit;
 
@@ -157,9 +187,18 @@
     TEST_ASSERT( mbedtls_pk_get_bitlen( &pk ) == bitlen );
     TEST_ASSERT( mbedtls_pk_get_len( &pk ) == bitlen / 8 );
 
-    TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECKEY ) == 1 );
-    TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECDSA ) == 1 );
-    TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_RSA ) == 0 );
+    if( key_is_rsa )
+    {
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECKEY ) == 0 );
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECDSA ) == 0 );
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_RSA ) == 1 );
+    }
+    else
+    {
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECKEY ) == 1 );
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_ECDSA ) == 1 );
+        TEST_ASSERT( mbedtls_pk_can_do( &pk, MBEDTLS_PK_RSA ) == 0 );
+    }
 
     /* unsupported operations: verify, decrypt, encrypt */
     TEST_ASSERT( mbedtls_pk_verify( &pk, md_alg,
@@ -175,8 +214,12 @@
                  == MBEDTLS_ERR_PK_TYPE_MISMATCH );
 
     /* unsupported functions: check_pair, debug */
-    TEST_ASSERT( mbedtls_pk_setup( &pk2,
-                 mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == 0 );
+    if( key_is_rsa )
+        TEST_ASSERT( mbedtls_pk_setup( &pk2,
+                     mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == 0 );
+    else
+        TEST_ASSERT( mbedtls_pk_setup( &pk2,
+                     mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == 0 );
     TEST_ASSERT( mbedtls_pk_check_pair( &pk, &pk2,
                                         mbedtls_test_rnd_std_rand, NULL )
                  == MBEDTLS_ERR_PK_TYPE_MISMATCH );
@@ -1006,14 +1049,13 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_SHA256_C:MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_ECDSA_C */
-void pk_psa_sign( int grpid_arg,
-                  int psa_curve_arg, int expected_bits_arg )
+/* BEGIN_CASE depends_on:MBEDTLS_SHA256_C:MBEDTLS_USE_PSA_CRYPTO */
+void pk_psa_sign( int parameter_arg,
+                  int psa_type_arg, int expected_bits_arg )
 {
-    mbedtls_ecp_group_id grpid = grpid_arg;
     mbedtls_pk_context pk;
     unsigned char hash[32];
-    unsigned char sig[MBEDTLS_ECDSA_MAX_LEN];
+    unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
     unsigned char pkey_legacy[200];
     unsigned char pkey_psa[200];
     unsigned char *pkey_legacy_start, *pkey_psa_start;
@@ -1021,12 +1063,12 @@
     int ret;
     mbedtls_svc_key_id_t key_id;
     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
-    psa_key_type_t expected_type = PSA_KEY_TYPE_ECC_KEY_PAIR( psa_curve_arg );
+    psa_key_type_t expected_type = psa_type_arg;
     size_t expected_bits = expected_bits_arg;
 
     /*
      * This tests making signatures with a wrapped PSA key:
-     * - generate a fresh ECP legacy PK context
+     * - generate a fresh ECP/RSA legacy PK context
      * - wrap it in a PK context and make a signature this way
      * - extract the public key
      * - parse it to a PK context and verify the signature this way
@@ -1034,13 +1076,38 @@
 
     PSA_ASSERT( psa_crypto_init( ) );
 
-    /* Create legacy EC public/private key in PK context. */
-    mbedtls_pk_init( &pk );
-    TEST_ASSERT( mbedtls_pk_setup( &pk,
-                      mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == 0 );
-    TEST_ASSERT( mbedtls_ecp_gen_key( grpid,
-                                      (mbedtls_ecp_keypair*) pk.pk_ctx,
-                                      mbedtls_test_rnd_std_rand, NULL ) == 0 );
+#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME)
+    if( PSA_KEY_TYPE_IS_RSA( psa_type_arg ) )
+    {
+        /* Create legacy RSA public/private key in PK context. */
+        mbedtls_pk_init( &pk );
+        TEST_ASSERT( mbedtls_pk_setup( &pk,
+                        mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == 0 );
+        TEST_ASSERT( mbedtls_rsa_gen_key( mbedtls_pk_rsa( pk ),
+                        mbedtls_test_rnd_std_rand, NULL,
+                        parameter_arg, 3 ) == 0 );
+    }
+    else
+#endif /* MBEDTLS_RSA_C && MBEDTLS_GENPRIME */
+#if defined(MBEDTLS_ECDSA_C)
+    if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( psa_type_arg ) )
+    {
+        mbedtls_ecp_group_id grpid = parameter_arg;
+
+        /* Create legacy EC public/private key in PK context. */
+        mbedtls_pk_init( &pk );
+        TEST_ASSERT( mbedtls_pk_setup( &pk,
+                        mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == 0 );
+        TEST_ASSERT( mbedtls_ecp_gen_key( grpid,
+                        (mbedtls_ecp_keypair*) pk.pk_ctx,
+                        mbedtls_test_rnd_std_rand, NULL ) == 0 );
+    }
+    else
+#endif /* MBEDTLS_ECDSA_C */
+    {
+        (void) parameter_arg;
+        TEST_ASSUME( ! "Opaque PK key not supported in this configuration" );
+    }
 
     /* Export underlying public key for re-importing in a legacy context. */
     ret = mbedtls_pk_write_pubkey_der( &pk, pkey_legacy,
diff --git a/tests/suites/test_suite_psa_crypto.data b/tests/suites/test_suite_psa_crypto.data
index 1a50749..ae24d63 100644
--- a/tests/suites/test_suite_psa_crypto.data
+++ b/tests/suites/test_suite_psa_crypto.data
@@ -2160,7 +2160,7 @@
 cipher_encrypt_validation:PSA_ALG_CBC_NO_PADDING:PSA_KEY_TYPE_DES:"01020407080b0d0ec1c2c4c7c8cbcdce31323437383b3d3e":"eda4011239bc3ac9"
 
 PSA symmetric encrypt validation: CCM*-no-tag, 15 bytes, good
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_encrypt_validation:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"d24a3d3dde8c84830280cb87abad0bb3":"6bc1bee22e409f96e93d7e11739317"
 
 PSA symmetric encrypt multipart: AES-ECB, 0 bytes, good
@@ -2224,7 +2224,7 @@
 cipher_encrypt_multipart:PSA_ALG_ECB_NO_PADDING:PSA_KEY_TYPE_DES:"01020407080b0d0ec1c2c4c7c8cbcdce31323437383b3d3e":"":"c78e2b38139610e3":8:8:0:"817ca7d69b80d86a":PSA_SUCCESS
 
 PSA symmetric encrypt multipart: CCM*-no-tag, AES, 24 bytes, good
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_encrypt_multipart:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"d24a3d3dde8c84830280cb87abad0bb3":"f1100035bb24a8d26004e0e24b":"7c86135ed9c2a515aaae0e9a208133897269220f30870006":10:10:14:"1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab":PSA_SUCCESS
 
 PSA cipher decrypt: without initialization
@@ -2260,7 +2260,7 @@
 cipher_decrypt_fail:PSA_ALG_CBC_NO_PADDING:PSA_KEY_TYPE_AES:"2b7e151628aed2a6abf7158809cf4f3c":"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a":"6bc1bee223":PSA_ERROR_INVALID_ARGUMENT
 
 PSA symetric decrypt: CCM*-no-tag, input too short (15 bytes)
-depends_on:MBEDTLS_AES_C:MBEDTLS_CCM_C
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:MBEDTLS_AES_C
 cipher_decrypt_fail:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"19ebfde2d5468ba0a3031bde629b11fd":"5a8aa485c316e9":"2a2a2a2a2a2a2a2a":PSA_ERROR_INVALID_ARGUMENT
 
 PSA symmetric decrypt: AES-ECB, 0 bytes, good
@@ -2312,7 +2312,7 @@
 cipher_decrypt:PSA_ALG_ECB_NO_PADDING:PSA_KEY_TYPE_DES:"01020407080b0d0ec1c2c4c7c8cbcdce31323437383b3d3e":"":"817ca7d69b80d86a":"c78e2b38139610e3"
 
 PSA symmetric decrypt: CCM*-no-tag, NIST DVPT AES-128 #15
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_decrypt:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"90929a4b0ac65b350ad1591611fe4829":"5a8aa485c316e9403aff859fbb":"4bfe4e35784f0a65b545477e5e2f4bae0e1e6fa717eaf2cb":"a16a2e741f1cd9717285b6d882c1fc53655e9773761ad697"
 
 PSA symmetric decrypt multipart: AES-ECB, 0 bytes, good
@@ -2376,7 +2376,7 @@
 cipher_decrypt_multipart:PSA_ALG_ECB_NO_PADDING:PSA_KEY_TYPE_DES:"01020407080b0d0ec1c2c4c7c8cbcdce31323437383b3d3e":"":"817ca7d69b80d86a":8:8:0:"c78e2b38139610e3":PSA_SUCCESS
 
 PSA symmetric decrypt multipart: CCM*-no-tag, 24 bytes, good
-depends_on:PSA_WANT_ALG_ECB_NO_PADDING:PSA_WANT_KEY_TYPE_DES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_decrypt_multipart:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"197afb02ffbd8f699dacae87094d5243":"5a8aa485c316e9403aff859fbb":"4a550134f94455979ec4bf89ad2bd80d25a77ae94e456134":10:10:14:"a16a2e741f1cd9717285b6d882c1fc53655e9773761ad697":PSA_SUCCESS
 
 PSA symmetric encrypt/decrypt: AES-ECB, 16 bytes, good
@@ -2400,19 +2400,19 @@
 cipher_verify_output:PSA_ALG_CTR:PSA_KEY_TYPE_AES:"2b7e151628aed2a6abf7158809cf4f3c":"6bc1bee22e409f96e93d7e117393172a"
 
 PSA symmetric encrypt/decrypt: CCM*-no-tag, AES
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_verify_output:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"2b7e151628aed2a6abf7158809cf4f3c":"6bc1bee22e409f96e93d7e117393172a"
 
 CCM*-no-tag encrypt, iv_length = 14, bad
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_encrypt_validate_iv_length:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"90929a4b0ac65b350ad1591611fe4829":"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a":14:PSA_ERROR_INVALID_ARGUMENT
 
 CCM*-no-tag encrypt, iv_length = 13, good
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_encrypt_validate_iv_length:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"90929a4b0ac65b350ad1591611fe4829":"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a":13:PSA_SUCCESS
 
 CCM*-no-tag encrypt, iv_length = 12, bad
-depends_on:PSA_WANT_ALG_CCM:PSA_WANT_KEY_TYPE_AES
+depends_on:PSA_WANT_ALG_CCM_STAR_NO_TAG:PSA_WANT_KEY_TYPE_AES
 cipher_encrypt_validate_iv_length:PSA_ALG_CCM_STAR_NO_TAG:PSA_KEY_TYPE_AES:"90929a4b0ac65b350ad1591611fe4829":"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a":12:PSA_ERROR_INVALID_ARGUMENT
 
 PSA symmetric encryption multipart: AES-ECB, 16+16 bytes
diff --git a/tests/suites/test_suite_psa_crypto_driver_wrappers.data b/tests/suites/test_suite_psa_crypto_driver_wrappers.data
index 210ab65..bf1e01b 100644
--- a/tests/suites/test_suite_psa_crypto_driver_wrappers.data
+++ b/tests/suites/test_suite_psa_crypto_driver_wrappers.data
@@ -780,3 +780,15 @@
 PSA encrypt transparent driver: fallback not available RSA OAEP-SHA-256
 depends_on:!MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP
 asymmetric_encrypt:PSA_ALG_RSA_OAEP(PSA_ALG_SHA_256):"30818902818100af057d396ee84fb75fdbb5c2b13c7fe5a654aa8aa2470b541ee1feb0b12d25c79711531249e1129628042dbbb6c120d1443524ef4c0e6e1d8956eeb2077af12349ddeee54483bc06c2c61948cd02b202e796aebd94d3a7cbf859c2c1819c324cb82b9cd34ede263a2abffe4733f077869e8660f7d6834da53d690ef7985f6bc30203010001":"af057d396ee84fb75fdbb5c2b13c7fe5a654aa8aa2470b541ee1feb0b12d25c79711531249e1129628042dbbb6c120d1443524ef4c0e6e1d8956eeb2077af12349ddeee54483bc06c2c61948cd02b202e796aebd94d3a7cbf859c2c1819c324cb82b9cd34ede263a2abffe4733f077869e8660f7d6834da53d690ef7985f6bc3":"874bf0ffc2f2a71d14671ddd0171c954d7fdbf50281e4f6d99ea0e1ebcf82faa58e7b595ffb293d1abe17f110b37c48cc0f36c37e84d876621d327f64bbe08457d3ec4098ba2fa0a319fba411c2841ed7be83196a8cdf9daa5d00694bc335fc4c32217fe0488bce9cb7202e59468b1ead119000477db2ca797fac19eda3f58c1":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad":"":"":PSA_ERROR_NOT_SUPPORTED:PSA_ERROR_NOT_SUPPORTED
+
+PSA multi-part AEAD encrypt setup, AES-GCM, 128 bytes #1
+depends_on:PSA_WANT_ALG_GCM:PSA_WANT_KEY_TYPE_AES
+aead_encrypt_setup:PSA_KEY_TYPE_AES:"a0ec7b0052541d9e9c091fb7fc481409":PSA_ALG_GCM:"00e440846db73a490573deaf3728c94f":"a3cfcb832e935eb5bc3812583b3a1b2e82920c07fda3668a35d939d8f11379bb606d39e6416b2ef336fffb15aec3f47a71e191f4ff6c56ff15913562619765b26ae094713d60bab6ab82bfc36edaaf8c7ce2cf5906554dcc5933acdb9cb42c1d24718efdc4a09256020b024b224cfe602772bd688c6c8f1041a46f7ec7d51208":"5431d93278c35cfcd7ffa9ce2de5c6b922edffd5055a9eaa5b54cae088db007cf2d28efaf9edd1569341889073e87c0a88462d77016744be62132fd14a243ed6e30e12cd2f7d08a8daeec161691f3b27d4996df8745d74402ee208e4055615a8cb069d495cf5146226490ac615d7b17ab39fb4fdd098e4e7ee294d34c1312826":"3b6de52f6e582d317f904ee768895bd4d0790912efcf27b58651d0eb7eb0b2f07222c6ffe9f7e127d98ccb132025b098a67dc0ec0083235e9f83af1ae1297df4319547cbcb745cebed36abc1f32a059a05ede6c00e0da097521ead901ad6a73be20018bda4c323faa135169e21581e5106ac20853642e9d6b17f1dd925c87281":"4365847fe0b7b7fbed325953df344a96":PSA_SUCCESS:PSA_SUCCESS
+
+PSA multi-part AEAD encrypt setup, AES-GCM, 128 bytes #1, fallback
+depends_on:MBEDTLS_AES_C:MBEDTLS_GCM_C
+aead_encrypt_setup:PSA_KEY_TYPE_AES:"a0ec7b0052541d9e9c091fb7fc481409":PSA_ALG_GCM:"00e440846db73a490573deaf3728c94f":"a3cfcb832e935eb5bc3812583b3a1b2e82920c07fda3668a35d939d8f11379bb606d39e6416b2ef336fffb15aec3f47a71e191f4ff6c56ff15913562619765b26ae094713d60bab6ab82bfc36edaaf8c7ce2cf5906554dcc5933acdb9cb42c1d24718efdc4a09256020b024b224cfe602772bd688c6c8f1041a46f7ec7d51208":"5431d93278c35cfcd7ffa9ce2de5c6b922edffd5055a9eaa5b54cae088db007cf2d28efaf9edd1569341889073e87c0a88462d77016744be62132fd14a243ed6e30e12cd2f7d08a8daeec161691f3b27d4996df8745d74402ee208e4055615a8cb069d495cf5146226490ac615d7b17ab39fb4fdd098e4e7ee294d34c1312826":"3b6de52f6e582d317f904ee768895bd4d0790912efcf27b58651d0eb7eb0b2f07222c6ffe9f7e127d98ccb132025b098a67dc0ec0083235e9f83af1ae1297df4319547cbcb745cebed36abc1f32a059a05ede6c00e0da097521ead901ad6a73be20018bda4c323faa135169e21581e5106ac20853642e9d6b17f1dd925c87281":"4365847fe0b7b7fbed325953df344a96":PSA_ERROR_NOT_SUPPORTED:PSA_SUCCESS
+
+PSA multi-part AEAD encrypt setup, AES-GCM, 128 bytes #1, INSUFFICIENT_MEMORY
+depends_on:PSA_WANT_ALG_GCM:PSA_WANT_KEY_TYPE_AES
+aead_encrypt_setup:PSA_KEY_TYPE_AES:"a0ec7b0052541d9e9c091fb7fc481409":PSA_ALG_GCM:"00e440846db73a490573deaf3728c94f":"a3cfcb832e935eb5bc3812583b3a1b2e82920c07fda3668a35d939d8f11379bb606d39e6416b2ef336fffb15aec3f47a71e191f4ff6c56ff15913562619765b26ae094713d60bab6ab82bfc36edaaf8c7ce2cf5906554dcc5933acdb9cb42c1d24718efdc4a09256020b024b224cfe602772bd688c6c8f1041a46f7ec7d51208":"5431d93278c35cfcd7ffa9ce2de5c6b922edffd5055a9eaa5b54cae088db007cf2d28efaf9edd1569341889073e87c0a88462d77016744be62132fd14a243ed6e30e12cd2f7d08a8daeec161691f3b27d4996df8745d74402ee208e4055615a8cb069d495cf5146226490ac615d7b17ab39fb4fdd098e4e7ee294d34c1312826":"3b6de52f6e582d317f904ee768895bd4d0790912efcf27b58651d0eb7eb0b2f07222c6ffe9f7e127d98ccb132025b098a67dc0ec0083235e9f83af1ae1297df4319547cbcb745cebed36abc1f32a059a05ede6c00e0da097521ead901ad6a73be20018bda4c323faa135169e21581e5106ac20853642e9d6b17f1dd925c87281":"4365847fe0b7b7fbed325953df344a96":PSA_ERROR_INSUFFICIENT_MEMORY:PSA_ERROR_INSUFFICIENT_MEMORY
diff --git a/tests/suites/test_suite_psa_crypto_driver_wrappers.function b/tests/suites/test_suite_psa_crypto_driver_wrappers.function
index 406432f..9e433bc 100644
--- a/tests/suites/test_suite_psa_crypto_driver_wrappers.function
+++ b/tests/suites/test_suite_psa_crypto_driver_wrappers.function
@@ -2328,3 +2328,123 @@
     PSA_DONE( );
 }
 /* END_CASE */
+
+/* BEGIN_CASE */
+void aead_encrypt_setup( int key_type_arg, data_t *key_data,
+                         int alg_arg,
+                         data_t *nonce,
+                         data_t *additional_data,
+                         data_t *input_data,
+                         data_t *expected_ciphertext,
+                         data_t *expected_tag,
+                         int forced_status_arg,
+                         int expected_status_arg )
+{
+    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    size_t key_bits;
+    psa_status_t forced_status = forced_status_arg;
+    psa_status_t expected_status = expected_status_arg;
+    uint8_t *output_data = NULL;
+    size_t output_size = 0;
+    size_t output_length = 0;
+    size_t finish_output_length = 0;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
+    size_t tag_length = 0;
+    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
+
+    psa_aead_operation_t operation = psa_aead_operation_init();
+
+    mbedtls_test_driver_aead_hooks = mbedtls_test_driver_aead_hooks_init();
+
+    PSA_INIT( );
+
+    mbedtls_test_driver_aead_hooks.forced_status = forced_status;
+
+    psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_ENCRYPT );
+    psa_set_key_algorithm( &attributes, alg );
+    psa_set_key_type( &attributes, key_type );
+
+    PSA_ASSERT( psa_import_key( &attributes, key_data->x, key_data->len,
+                                &key ) );
+    PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
+    key_bits = psa_get_key_bits( &attributes );
+
+    output_size = input_data->len + PSA_AEAD_TAG_LENGTH( key_type, key_bits,
+                                                         alg );
+
+    /* For all currently defined algorithms, PSA_AEAD_ENCRYPT_OUTPUT_SIZE
+     * should be exact. */
+    TEST_EQUAL( output_size,
+                PSA_AEAD_ENCRYPT_OUTPUT_SIZE( key_type, alg, input_data->len ) );
+    TEST_ASSERT( output_size <=
+                 PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE( input_data->len ) );
+    ASSERT_ALLOC( output_data, output_size );
+
+    status = psa_aead_encrypt_setup( &operation, key, alg );
+
+    TEST_EQUAL( status, expected_status );
+    TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_encrypt_setup, 1 );
+
+    if( status == PSA_SUCCESS )
+    {
+        /* Set the nonce. */
+        PSA_ASSERT( psa_aead_set_nonce( &operation, nonce->x, nonce->len ) );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_set_nonce,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        /* Check hooks hits and
+         * set length (additional data and data to encrypt) */
+        PSA_ASSERT( psa_aead_set_lengths( &operation, additional_data->len,
+                                          input_data->len ) );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_set_lengths,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        /* Pass the additional data */
+        PSA_ASSERT( psa_aead_update_ad( &operation, additional_data->x,
+                                        additional_data->len ) );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_update_ad,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        /* Pass the data to encrypt */
+        PSA_ASSERT( psa_aead_update( &operation, input_data->x, input_data->len,
+                                     output_data, output_size, &output_length ) );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_update,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        /* Finish the encryption operation */
+        PSA_ASSERT( psa_aead_finish( &operation, output_data + output_length,
+                                     output_size - output_length,
+                                     &finish_output_length, tag_buffer,
+                                     PSA_AEAD_TAG_MAX_SIZE, &tag_length ) );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_finish,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        TEST_EQUAL( mbedtls_test_driver_aead_hooks.hits_abort,
+                    forced_status == PSA_SUCCESS ? 1 : 0 );
+
+        /* Compare output_data and expected_ciphertext */
+        ASSERT_COMPARE( expected_ciphertext->x, expected_ciphertext->len,
+                        output_data, output_length );
+
+        TEST_EQUAL( output_length + finish_output_length, expected_ciphertext->len );
+
+        /* Compare tag and expected_tag */
+        ASSERT_COMPARE( expected_tag->x, expected_tag->len, tag_buffer, tag_length );
+    }
+
+exit:
+    /* Cleanup */
+    PSA_ASSERT( psa_destroy_key( key ) );
+    mbedtls_free( output_data );
+    PSA_DONE( );
+    mbedtls_test_driver_aead_hooks = mbedtls_test_driver_aead_hooks_init();
+}
+/* END_CASE */
diff --git a/tests/suites/test_suite_psa_crypto_op_fail.function b/tests/suites/test_suite_psa_crypto_op_fail.function
new file mode 100644
index 0000000..8b50f10
--- /dev/null
+++ b/tests/suites/test_suite_psa_crypto_op_fail.function
@@ -0,0 +1,390 @@
+/* BEGIN_HEADER */
+
+#include "psa/crypto.h"
+#include "test/psa_crypto_helpers.h"
+
+static int test_equal_status( const char *test,
+                              int line_no, const char* filename,
+                              psa_status_t value1,
+                              psa_status_t value2 )
+{
+    if( ( value1 == PSA_ERROR_INVALID_ARGUMENT &&
+          value2 == PSA_ERROR_NOT_SUPPORTED ) ||
+        ( value1 == PSA_ERROR_NOT_SUPPORTED &&
+          value2 == PSA_ERROR_INVALID_ARGUMENT ) )
+    {
+        return( 1 );
+    }
+    return( mbedtls_test_equal( test, line_no, filename, value1, value2 ) );
+}
+
+/** Like #TEST_EQUAL, but expects #psa_status_t values and treats
+ * #PSA_ERROR_INVALID_ARGUMENT and #PSA_ERROR_NOT_SUPPORTED as
+ * interchangeable.
+ *
+ * This test suite currently allows NOT_SUPPORTED and INVALID_ARGUMENT
+ * to be interchangeable in places where the library's behavior does not
+ * match the strict expectations of the test case generator. In the long
+ * run, it would be better to clarify the expectations and reconcile the
+ * library and the test case generator.
+ */
+#define TEST_STATUS( expr1, expr2 )                                     \
+    do {                                                                \
+        if( ! test_equal_status( #expr1 " == " #expr2, __LINE__, __FILE__, \
+                                 expr1, expr2 ) )                       \
+            goto exit;                                                  \
+    } while( 0 )
+
+/* END_HEADER */
+
+/* BEGIN_DEPENDENCIES
+ * depends_on:MBEDTLS_PSA_CRYPTO_C
+ * END_DEPENDENCIES
+ */
+
+/* BEGIN_CASE */
+void hash_fail( int alg_arg, int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
+    uint8_t input[1] = {'A'};
+    uint8_t output[PSA_HASH_MAX_SIZE] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    TEST_EQUAL( expected_status,
+                psa_hash_setup( &operation, alg ) );
+    TEST_EQUAL( expected_status,
+                psa_hash_compute( alg, input, sizeof( input ),
+                                  output, sizeof( output ), &length ) );
+    TEST_EQUAL( expected_status,
+                psa_hash_compare( alg, input, sizeof( input ),
+                                  output, sizeof( output ) ) );
+
+exit:
+    psa_hash_abort( &operation );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void mac_fail( int key_type_arg, data_t *key_data,
+               int alg_arg, int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t input[1] = {'A'};
+    uint8_t output[PSA_MAC_MAX_SIZE] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_SIGN_HASH |
+                             PSA_KEY_USAGE_VERIFY_HASH );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+
+    TEST_STATUS( expected_status,
+                 psa_mac_sign_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_mac_verify_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_mac_compute( key_id, alg,
+                                  input, sizeof( input ),
+                                  output, sizeof( output ), &length ) );
+    TEST_STATUS( expected_status,
+                 psa_mac_verify( key_id, alg,
+                                 input, sizeof( input ),
+                                 output, sizeof( output ) ) );
+
+exit:
+    psa_mac_abort( &operation );
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void cipher_fail( int key_type_arg, data_t *key_data,
+                  int alg_arg, int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t input[1] = {'A'};
+    uint8_t output[64] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_ENCRYPT |
+                             PSA_KEY_USAGE_DECRYPT );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+
+    TEST_STATUS( expected_status,
+                 psa_cipher_encrypt_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_cipher_decrypt_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_cipher_encrypt( key_id, alg,
+                                     input, sizeof( input ),
+                                     output, sizeof( output ), &length ) );
+    TEST_STATUS( expected_status,
+                 psa_cipher_decrypt( key_id, alg,
+                                     input, sizeof( input ),
+                                     output, sizeof( output ), &length ) );
+
+exit:
+    psa_cipher_abort( &operation );
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void aead_fail( int key_type_arg, data_t *key_data,
+                int alg_arg, int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t input[16] = "ABCDEFGHIJKLMNO";
+    uint8_t output[64] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_ENCRYPT |
+                             PSA_KEY_USAGE_DECRYPT );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+
+    TEST_STATUS( expected_status,
+                 psa_aead_encrypt_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_aead_decrypt_setup( &operation, key_id, alg ) );
+    TEST_STATUS( expected_status,
+                 psa_aead_encrypt( key_id, alg,
+                                   input, sizeof( input ),
+                                   NULL, 0, input, sizeof( input ),
+                                   output, sizeof( output ), &length ) );
+    TEST_STATUS( expected_status,
+                 psa_aead_decrypt( key_id, alg,
+                                   input, sizeof( input ),
+                                   NULL, 0, input, sizeof( input ),
+                                   output, sizeof( output ), &length ) );
+
+exit:
+    psa_aead_abort( &operation );
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void sign_fail( int key_type_arg, data_t *key_data,
+                int alg_arg, int private_only,
+                int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t input[1] = {'A'};
+    uint8_t output[PSA_SIGNATURE_MAX_SIZE] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_SIGN_HASH |
+                             PSA_KEY_USAGE_VERIFY_HASH );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+
+    TEST_STATUS( expected_status,
+                 psa_sign_hash( key_id, alg,
+                                input, sizeof( input ),
+                                output, sizeof( output ), &length ) );
+    if( ! private_only )
+    {
+        /* Determine a plausible signature size to avoid an INVALID_SIGNATURE
+         * error based on this. */
+        PSA_ASSERT( psa_get_key_attributes( key_id, &attributes ) );
+        size_t key_bits = psa_get_key_bits( &attributes );
+        size_t output_length = sizeof( output );
+        if( PSA_KEY_TYPE_IS_RSA( key_type ) )
+            output_length = PSA_BITS_TO_BYTES( key_bits );
+        else if( PSA_KEY_TYPE_IS_ECC( key_type ) )
+            output_length = 2 * PSA_BITS_TO_BYTES( key_bits );
+        TEST_ASSERT( output_length <= sizeof( output ) );
+        TEST_STATUS( expected_status,
+                     psa_verify_hash( key_id, alg,
+                                      input, sizeof( input ),
+                                      output, output_length ) );
+    }
+
+exit:
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void asymmetric_encryption_fail( int key_type_arg, data_t *key_data,
+                                 int alg_arg, int private_only,
+                                 int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t plaintext[PSA_ASYMMETRIC_DECRYPT_OUTPUT_MAX_SIZE] = {0};
+    uint8_t ciphertext[PSA_ASYMMETRIC_ENCRYPT_OUTPUT_MAX_SIZE] = {0};
+    size_t length = SIZE_MAX;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_ENCRYPT |
+                             PSA_KEY_USAGE_DECRYPT );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+
+    if( ! private_only )
+    {
+        TEST_STATUS( expected_status,
+                     psa_asymmetric_encrypt( key_id, alg,
+                                             plaintext, 1,
+                                             NULL, 0,
+                                             ciphertext, sizeof( ciphertext ),
+                                             &length ) );
+    }
+    TEST_STATUS( expected_status,
+                 psa_asymmetric_decrypt( key_id, alg,
+                                         ciphertext, sizeof( ciphertext ),
+                                         NULL, 0,
+                                         plaintext, sizeof( plaintext ),
+                                         &length ) );
+
+exit:
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void key_derivation_fail( int alg_arg, int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
+
+    PSA_INIT( );
+
+    TEST_EQUAL( expected_status,
+                psa_key_derivation_setup( &operation, alg ) );
+
+exit:
+    psa_key_derivation_abort( &operation );
+    PSA_DONE( );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void key_agreement_fail( int key_type_arg, data_t *key_data,
+                         int alg_arg, int private_only,
+                         int expected_status_arg )
+{
+    psa_status_t expected_status = expected_status_arg;
+    psa_key_type_t key_type = key_type_arg;
+    psa_algorithm_t alg = alg_arg;
+    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+    mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+    uint8_t public_key[PSA_EXPORT_PUBLIC_KEY_MAX_SIZE] = {0};
+    size_t public_key_length = SIZE_MAX;
+    uint8_t output[PSA_SIGNATURE_MAX_SIZE] = {0};
+    size_t length = SIZE_MAX;
+    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
+
+    PSA_INIT( );
+
+    psa_set_key_type( &attributes, key_type );
+    psa_set_key_usage_flags( &attributes,
+                             PSA_KEY_USAGE_DERIVE );
+    psa_set_key_algorithm( &attributes, alg );
+    PSA_ASSERT( psa_import_key( &attributes,
+                                key_data->x, key_data->len,
+                                &key_id ) );
+    if( PSA_KEY_TYPE_IS_KEY_PAIR( key_type ) ||
+        PSA_KEY_TYPE_IS_PUBLIC_KEY( key_type ) )
+    {
+        PSA_ASSERT( psa_export_public_key( key_id,
+                                           public_key, sizeof( public_key ),
+                                           &public_key_length ) );
+    }
+
+    TEST_STATUS( expected_status,
+                 psa_raw_key_agreement( alg, key_id,
+                                        public_key, public_key_length,
+                                        output, sizeof( output ), &length ) );
+
+#if defined(PSA_WANT_ALG_HKDF) && defined(PSA_WANT_ALG_SHA_256)
+    PSA_ASSERT( psa_key_derivation_setup( &operation,
+                                          PSA_ALG_HKDF( PSA_ALG_SHA_256 ) ) );
+    TEST_STATUS( expected_status,
+                 psa_key_derivation_key_agreement(
+                     &operation,
+                     PSA_KEY_DERIVATION_INPUT_SECRET,
+                     key_id,
+                     public_key, public_key_length ) );
+#endif
+
+    /* There are no public-key operations. */
+    (void) private_only;
+
+exit:
+    psa_key_derivation_abort( &operation );
+    psa_destroy_key( key_id );
+    psa_reset_key_attributes( &attributes );
+    PSA_DONE( );
+}
+/* END_CASE */
diff --git a/tests/suites/test_suite_psa_crypto_op_fail.misc.data b/tests/suites/test_suite_psa_crypto_op_fail.misc.data
new file mode 100644
index 0000000..147c3b7
--- /dev/null
+++ b/tests/suites/test_suite_psa_crypto_op_fail.misc.data
@@ -0,0 +1,15 @@
+# Most operation failure test cases are automatically generated in
+# test_suite_psa_crypto_op_fail.generated.data. The manually written
+# test cases in this file are only intended to help with debugging the
+# test code.
+
+PSA hash: invalid algorithm
+hash_fail:PSA_ALG_ECDSA_ANY:PSA_ERROR_INVALID_ARGUMENT
+
+PSA sign RSA_PSS(SHA_256): incompatible key type
+depends_on:PSA_WANT_ALG_RSA_PSS:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_AES
+sign_fail:PSA_KEY_TYPE_AES:"48657265006973206b6579a064617461":PSA_ALG_RSA_PSS(PSA_ALG_SHA_256):0:PSA_ERROR_INVALID_ARGUMENT
+
+PSA sign RSA_PSS(SHA_256): RSA_PSS not enabled, key pair
+depends_on:!PSA_WANT_ALG_RSA_PSS:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_RSA_KEY_PAIR
+sign_fail:PSA_KEY_TYPE_RSA_KEY_PAIR:"3082025e02010002818100af057d396ee84fb75fdbb5c2b13c7fe5a654aa8aa2470b541ee1feb0b12d25c79711531249e1129628042dbbb6c120d1443524ef4c0e6e1d8956eeb2077af12349ddeee54483bc06c2c61948cd02b202e796aebd94d3a7cbf859c2c1819c324cb82b9cd34ede263a2abffe4733f077869e8660f7d6834da53d690ef7985f6bc3020301000102818100874bf0ffc2f2a71d14671ddd0171c954d7fdbf50281e4f6d99ea0e1ebcf82faa58e7b595ffb293d1abe17f110b37c48cc0f36c37e84d876621d327f64bbe08457d3ec4098ba2fa0a319fba411c2841ed7be83196a8cdf9daa5d00694bc335fc4c32217fe0488bce9cb7202e59468b1ead119000477db2ca797fac19eda3f58c1024100e2ab760841bb9d30a81d222de1eb7381d82214407f1b975cbbfe4e1a9467fd98adbd78f607836ca5be1928b9d160d97fd45c12d6b52e2c9871a174c66b488113024100c5ab27602159ae7d6f20c3c2ee851e46dc112e689e28d5fcbbf990a99ef8a90b8bb44fd36467e7fc1789ceb663abda338652c3c73f111774902e840565927091024100b6cdbd354f7df579a63b48b3643e353b84898777b48b15f94e0bfc0567a6ae5911d57ad6409cf7647bf96264e9bd87eb95e263b7110b9a1f9f94acced0fafa4d024071195eec37e8d257decfc672b07ae639f10cbb9b0c739d0c809968d644a94e3fd6ed9287077a14583f379058f76a8aecd43c62dc8c0f41766650d725275ac4a1024100bb32d133edc2e048d463388b7be9cb4be29f4b6250be603e70e3647501c97ddde20a4e71be95fd5e71784e25aca4baf25be5738aae59bbfe1c997781447a2b24":PSA_ALG_RSA_PSS(PSA_ALG_SHA_256):0:PSA_ERROR_NOT_SUPPORTED
diff --git a/tests/suites/test_suite_timing.data b/tests/suites/test_suite_timing.data
index a45ed0e..de89239 100644
--- a/tests/suites/test_suite_timing.data
+++ b/tests/suites/test_suite_timing.data
@@ -1,11 +1,8 @@
 Timing: get timer
-depends_on:MBEDTLS_HAVE_TIME
 timing_get_timer:
 
 Timing: delay 0ms
-depends_on:MBEDTLS_HAVE_TIME
 timing_delay:0:
 
 Timing: delay 100ms
-depends_on:MBEDTLS_HAVE_TIME
 timing_delay:100: