Cryptography Reference
In-Depth Information
store the length. A sole “1” bit follows the last bit of input, followed by enough
0's to pad up to 448 bits, followed by the length of the message itself in bits.
NOTE According to the specifi cation, if the length is greater than 2 64 bits,
you can throw away the high-order bits of the length. This won't come up with
any of the values that are hashed in this topic.
Now, the MD5 specifi cation has a strange formulation for the length. Rather
than just being a little-endian 64-bit integer, it's instead stored as “low-order 32
bits” and “high-order 32 bits.”
The code to process an arbitrarily sized input into an MD5 hash, including
padding and iteration over multiple blocks, is shown in Listing 4-7.
Listing 4-7: “md5.c” md5 hash algorithm
#define MD5_BLOCK_SIZE 64
#define MD5_INPUT_BLOCK_SIZE 56
#define MD5_RESULT_SIZE 4
int md5_hash( const unsigned char *input,
int len,
unsigned int hash[ MD5_RESULT_SIZE ] )
{
unsigned char padded_block[ MD5_BLOCK_SIZE ];
int length_in_bits = len * 8;
// XXX should verify that len < 2^64, but since len is only 32 bits, this won't
// be a problem.
hash[ 0 ] = md5_initial_hash[ 0 ];
hash[ 1 ] = md5_initial_hash[ 1 ];
hash[ 2 ] = md5_initial_hash[ 2 ];
hash[ 3 ] = md5_initial_hash[ 3 ];
while ( len >= MD5_INPUT_BLOCK_SIZE )
{
// Special handling for blocks between 56 and 64 bytes
// (not enough room for the 8 bytes of length, but also
// not enough to fill up a block)
if ( len < MD5_BLOCK_SIZE )
{
memset( padded_block, 0, sizeof( padded_block ) );
memcpy( padded_block, input, len );
padded_block[ len ] = 0x80;
md5_block_operate( padded_block, hash );
input += len;
len = -1;
(Continued)
 
Search WWH ::




Custom Search