psa_export_key: zero out potential garbage in the output buffer
In psa_export_key, ensure that each byte of the output buffer either
contains its original value, is zero, or is part of the actual output.
Specifically, don't risk having partial output on error, and don't
leave extra data at the end of the buffer when exporting an asymmetric
key.
Test that exporting to a previously zeroed buffer leaves the buffer
zeroed outside the actual output if any.
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index c552b53..8e7aeef 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -628,17 +628,22 @@
else
ret = mbedtls_pk_write_key_der( &pk, data, data_size );
if( ret < 0 )
+ {
+ memset( data, 0, data_size );
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 );
+ memset( data + data_size - ret, 0, ret );
}
else if( (size_t) ret < data_size )
{
memmove( data, data + data_size - ret, ret );
+ memset( data + ret, 0, data_size - ret );
}
*data_length = ret;
return( PSA_SUCCESS );