Implement extended master secret
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 065f3a8..d7b16b8 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -2326,12 +2326,6 @@
         return( POLARSSL_ERR_SSL_INTERNAL_ERROR );
     }
 
-    if( ( ret = ssl_derive_keys( ssl ) ) != 0 )
-    {
-        SSL_DEBUG_RET( 1, "ssl_derive_keys", ret );
-        return( ret );
-    }
-
     ssl->out_msglen  = i + n;
     ssl->out_msgtype = SSL_MSG_HANDSHAKE;
     ssl->out_msg[0]  = SSL_HS_CLIENT_KEY_EXCHANGE;
@@ -2356,9 +2350,16 @@
 static int ssl_write_certificate_verify( ssl_context *ssl )
 {
     const ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
+    int ret;
 
     SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
 
+    if( ( ret = ssl_derive_keys( ssl ) ) != 0 )
+    {
+        SSL_DEBUG_RET( 1, "ssl_derive_keys", ret );
+        return( ret );
+    }
+
     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_RSA_PSK ||
         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK ||
@@ -2385,6 +2386,12 @@
 
     SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
 
+    if( ( ret = ssl_derive_keys( ssl ) ) != 0 )
+    {
+        SSL_DEBUG_RET( 1, "ssl_derive_keys", ret );
+        return( ret );
+    }
+
     if( ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_PSK ||
         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_RSA_PSK ||
         ciphersuite_info->key_exchange == POLARSSL_KEY_EXCHANGE_ECDHE_PSK ||