Merge branch 'pr_1276' into mbedtls-2.1-proposed
diff --git a/ChangeLog b/ChangeLog
index 392e747..d95379c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -39,6 +39,11 @@
      overflow. #1179
    * Fix memory allocation corner cases in memory_buffer_alloc.c module. Found
      by Guido Vranken. #639
+   * Fix the entropy.c module to ensure that mbedtls_sha256_init() or
+     mbedtls_sha512_init() is called before operating on the relevant context
+     structure. Do not assume that zeroizing a context is a correct way to
+     reset it. Found independently by ccli8 on Github.
+   * In mbedtls_entropy_free(), properly free the message digest context.
 
 Changes
    * Clarified the documentation of mbedtls_ssl_setup.
diff --git a/library/entropy.c b/library/entropy.c
index 5cef78c..b0a94d0 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -68,8 +68,10 @@
 #endif
 
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
+    mbedtls_sha512_init( &ctx->accumulator );
     mbedtls_sha512_starts( &ctx->accumulator, 0 );
 #else
+    mbedtls_sha256_init( &ctx->accumulator );
     mbedtls_sha256_starts( &ctx->accumulator, 0 );
 #endif
 #if defined(MBEDTLS_HAVEGE_C)
@@ -105,6 +107,13 @@
 #if defined(MBEDTLS_HAVEGE_C)
     mbedtls_havege_free( &ctx->havege_data );
 #endif
+
+#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
+    mbedtls_sha512_free( &ctx->accumulator );
+#else
+    mbedtls_sha256_free( &ctx->accumulator );
+#endif
+
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_mutex_free( &ctx->mutex );
 #endif
@@ -314,7 +323,8 @@
     /*
      * Reset accumulator and counters and recycle existing entropy
      */
-    memset( &ctx->accumulator, 0, sizeof( mbedtls_sha512_context ) );
+    mbedtls_sha512_free( &ctx->accumulator );
+    mbedtls_sha512_init( &ctx->accumulator );
     mbedtls_sha512_starts( &ctx->accumulator, 0 );
     mbedtls_sha512_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
 
@@ -328,7 +338,8 @@
     /*
      * Reset accumulator and counters and recycle existing entropy
      */
-    memset( &ctx->accumulator, 0, sizeof( mbedtls_sha256_context ) );
+    mbedtls_sha256_free( &ctx->accumulator );
+    mbedtls_sha256_init( &ctx->accumulator );
     mbedtls_sha256_starts( &ctx->accumulator, 0 );
     mbedtls_sha256_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );