Add _init() and _free() for hash modules
diff --git a/library/sha1.c b/library/sha1.c
index a528d8e..20408c7 100644
--- a/library/sha1.c
+++ b/library/sha1.c
@@ -78,6 +78,19 @@
}
#endif
+void sha1_init( sha1_context *ctx )
+{
+ memset( ctx, 0, sizeof( sha1_context ) );
+}
+
+void sha1_free( sha1_context *ctx )
+{
+ if( ctx == NULL )
+ return;
+
+ polarssl_zeroize( ctx, sizeof( sha1_context ) );
+}
+
/*
* SHA-1 context setup
*/
@@ -335,11 +348,11 @@
{
sha1_context ctx;
+ sha1_init( &ctx );
sha1_starts( &ctx );
sha1_update( &ctx, input, ilen );
sha1_finish( &ctx, output );
-
- polarssl_zeroize( &ctx, sizeof( sha1_context ) );
+ sha1_free( &ctx );
}
#if defined(POLARSSL_FS_IO)
@@ -356,14 +369,14 @@
if( ( f = fopen( path, "rb" ) ) == NULL )
return( POLARSSL_ERR_SHA1_FILE_IO_ERROR );
+ sha1_init( &ctx );
sha1_starts( &ctx );
while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
sha1_update( &ctx, buf, n );
sha1_finish( &ctx, output );
-
- polarssl_zeroize( &ctx, sizeof( sha1_context ) );
+ sha1_free( &ctx );
if( ferror( f ) != 0 )
{
@@ -450,11 +463,11 @@
{
sha1_context ctx;
+ sha1_init( &ctx );
sha1_hmac_starts( &ctx, key, keylen );
sha1_hmac_update( &ctx, input, ilen );
sha1_hmac_finish( &ctx, output );
-
- polarssl_zeroize( &ctx, sizeof( sha1_context ) );
+ sha1_free( &ctx );
}
#if defined(POLARSSL_SELF_TEST)
@@ -554,11 +567,13 @@
*/
int sha1_self_test( int verbose )
{
- int i, j, buflen;
+ int i, j, buflen, ret = 0;
unsigned char buf[1024];
unsigned char sha1sum[20];
sha1_context ctx;
+ sha1_init( &ctx );
+
/*
* SHA-1
*/
@@ -587,7 +602,8 @@
if( verbose != 0 )
polarssl_printf( "failed\n" );
- return( 1 );
+ ret = 1;
+ goto exit;
}
if( verbose != 0 )
@@ -623,7 +639,8 @@
if( verbose != 0 )
polarssl_printf( "failed\n" );
- return( 1 );
+ ret = 1;
+ goto exit;
}
if( verbose != 0 )
@@ -633,7 +650,10 @@
if( verbose != 0 )
polarssl_printf( "\n" );
- return( 0 );
+exit:
+ sha1_free( &ctx );
+
+ return( ret );
}
#endif /* POLARSSL_SELF_TEST */