psa_export_key: fix asymmetric key in larger buffer
Exporting an asymmetric key only worked if the target buffer had
exactly the right size, because psa_export_key uses
mbedtls_pk_write_key_der or mbedtls_pk_write_pubkey_der and these
functions write to the end of the buffer, which psa_export_key did not
correct for. Fix this by moving the data to the beginning of the
buffer if necessary.
Add non-regression tests.
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index 5609f42..c552b53 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -629,6 +629,17 @@
ret = mbedtls_pk_write_key_der( &pk, data, data_size );
if( ret < 0 )
return( mbedtls_to_psa_error( ret ) );
+ /* The mbedtls_pk_xxx functions write to the end of the buffer.
+ * Move the data to the beginning and erase remaining data
+ * at the original location. */
+ if( 2 * (size_t) ret <= data_size )
+ {
+ memcpy( data, data + data_size - ret, ret );
+ }
+ else if( (size_t) ret < data_size )
+ {
+ memmove( data, data + data_size - ret, ret );
+ }
*data_length = ret;
return( PSA_SUCCESS );
}