Cryptography Reference
In-Depth Information
the end of it, process the resulting block, and process whatever remaining
blocks are left.
if ( context->block_len > 0 )
{
// How much we need to make a full block
int borrow_amt = DIGEST_BLOCK_SIZE - context->block_len;
if ( input_len < borrow_amt )
{
5. borrow_amt is the number of bytes needed to make a full block. If you
still don't have enough, just add it to the end of the temporary block and
allow the function to exit.
memcpy( context->block context->block_len, input, input_len );
context->block_len = input_len;
input_len = 0;
}
Otherwise, go ahead and copy borrow_amt bytes into the temporary block,
process that block, and continue:
else
{
memcpy( context->block context->block_len, input, borrow_amt );
context->block_operate( context->block, context->hash );
context->block_len = 0;
input = borrow_amt;
input_len -= borrow_amt;
}
Appending the Length to the Last Block
So, the caller calls update_digest repeatedly, as data becomes available, allow-
ing it to compute a running hash code. However, to complete an MD5 or SHA-1
hash, you still have to append the length, in bits, to the end of the last block. The
function finalize_digest handles what used to be the complex logic in digest_
hash to fi gure out if the remaining data consists of one or two blocks — that is,
if there's enough space for the end terminator and the length on the end of the
remaining block as shown in Listing 4-23.
Listing 4-23: “digest.c” fi nalize digest
/**
* Process whatever's left over in the context buffer, append
* the length in bits, and update the hash one last time.
*/
void finalize_digest( digest_ctx *context )
{
memset( context->block + context->block_len, 0, DIGEST_BLOCK_SIZE -
 
Search WWH ::




Custom Search