Save memory by not storing the HMAC key
diff --git a/include/polarssl/hmac_drbg.h b/include/polarssl/hmac_drbg.h
index 640eb0c..7f30c04 100644
--- a/include/polarssl/hmac_drbg.h
+++ b/include/polarssl/hmac_drbg.h
@@ -56,11 +56,11 @@
*/
typedef struct
{
- /* Working state */
- md_context_t md_ctx; /*!< HMAC context */
- unsigned char V[POLARSSL_MD_MAX_SIZE]; /*!< V in the spec */
- unsigned char K[POLARSSL_MD_MAX_SIZE]; /*!< Key in the spec */
- int reseed_counter; /*!< reseed counter */
+ /* Working state: the key K is not stored explicitely,
+ * but is implied by the HMAC context */
+ md_context_t md_ctx; /*!< HMAC context (inc. K) */
+ unsigned char V[POLARSSL_MD_MAX_SIZE]; /*!< V in the spec */
+ int reseed_counter; /*!< reseed counter */
/* Administrative state */
size_t entropy_len; /*!< entropy bytes grabbed on each (re)seed */
diff --git a/library/hmac_drbg.c b/library/hmac_drbg.c
index f186b5c..33a20ef 100644
--- a/library/hmac_drbg.c
+++ b/library/hmac_drbg.c
@@ -48,19 +48,20 @@
size_t md_len = ctx->md_ctx.md_info->size;
unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;
unsigned char sep[1];
+ unsigned char K[POLARSSL_MD_MAX_SIZE];
for( sep[0] = 0; sep[0] < rounds; sep[0]++ )
{
/* Step 1 or 4 */
- md_hmac_starts( &ctx->md_ctx, ctx->K, md_len );
+ md_hmac_reset( &ctx->md_ctx );
md_hmac_update( &ctx->md_ctx, ctx->V, md_len );
md_hmac_update( &ctx->md_ctx, sep, 1 );
if( rounds == 2 )
md_hmac_update( &ctx->md_ctx, additional, add_len );
- md_hmac_finish( &ctx->md_ctx, ctx->K );
+ md_hmac_finish( &ctx->md_ctx, K );
/* Step 2 or 5 */
- md_hmac_starts( &ctx->md_ctx, ctx->K, md_len );
+ md_hmac_starts( &ctx->md_ctx, K, md_len );
md_hmac_update( &ctx->md_ctx, ctx->V, md_len );
md_hmac_finish( &ctx->md_ctx, ctx->V );
}
@@ -80,8 +81,13 @@
if( ( ret = md_init_ctx( &ctx->md_ctx, md_info ) ) != 0 )
return( ret );
+ /*
+ * Set initial working state.
+ * Use the V memory location, which is currently all 0, to initialize the
+ * MD context with an all-zero key. Then set V to its initial value.
+ */
+ md_hmac_starts( &ctx->md_ctx, ctx->V, md_info->size );
memset( ctx->V, 0x01, md_info->size );
- /* ctx->K is already 0 */
hmac_drbg_update( ctx, data, data_len );
@@ -147,9 +153,13 @@
if( ( ret = md_init_ctx( &ctx->md_ctx, md_info ) ) != 0 )
return( ret );
- /* Set initial working state */
+ /*
+ * Set initial working state.
+ * Use the V memory location, which is currently all 0, to initialize the
+ * MD context with an all-zero key. Then set V to its initial value.
+ */
+ md_hmac_starts( &ctx->md_ctx, ctx->V, md_info->size );
memset( ctx->V, 0x01, md_info->size );
- /* ctx->K is already 0 */
ctx->f_entropy = f_entropy;
ctx->p_entropy = p_entropy;