Cryptography Reference
In-Depth Information
Listing 4-10: “digest.h” digest_hash function prototype
int digest_hash( unsigned char *input,
int len,
unsigned int *hash,
void (*block_operate)(const unsigned char *input, unsigned int hash[] ));
Because SHA1_BLOCK_SIZE and MD5_BLOCK_SIZE are actually identical, there's
not much benefi t in using two different constants. You could pass the block
size in as a parameter to increase fl exibility, but there are already quite a few
parameters, and you don't need this fl exibility — at least not yet. The initializa-
tion is different because SHA has one extra four-byte integer, but you can just
initialize outside of the function to take care of that.
Understanding SHA-1 Finalization
The only remaining difference is the fi nalization. Remember that MD5 had
sort of an odd formulation to append the length to the end of the block in little-
endian format. SHA doesn't; it sticks with the standard big endian. You could
probably code your way around this, but a better approach is to just refactor
this into another function in Listing 4-11 and Listing 4-12.
Listing 4-11: “md5.c” md5_fi nalize
void md5_finalize( unsigned char *padded_block, int length_in_bits )
{
padded_block[ MD5_BLOCK_SIZE - 5 ] = ( length_in_bits & 0xFF000000 ) >> 24;
padded_block[ MD5_BLOCK_SIZE - 6 ] = ( length_in_bits & 0x00FF0000 ) >> 16;
padded_block[ MD5_BLOCK_SIZE - 7 ] = ( length_in_bits & 0x0000FF00 ) >> 8;
padded_block[ MD5_BLOCK_SIZE - 8 ] = ( length_in_bits & 0x000000FF );
}
Listing 4-12: “sha.c” sha1_fi nalize
void sha1_finalize( unsigned char *padded_block, int length_in_bits )
{
padded_block[ SHA1_BLOCK_SIZE - 4 ] = ( length_in_bits & 0xFF000000 ) >> 24;
padded_block[ SHA1_BLOCK_SIZE - 3 ] = ( length_in_bits & 0x00FF0000 ) >> 16;
padded_block[ SHA1_BLOCK_SIZE - 2 ] = ( length_in_bits & 0x0000FF00 ) >> 8;
padded_block[ SHA1_BLOCK_SIZE - 1 ] = ( length_in_bits & 0x000000FF );
}
So the fi nal “digest” function looks like Listing 4-13, with two function
parameters.
Listing 4-13: “digest.c” digest _hash
#define DIGEST_BLOCK_SIZE 64
#define INPUT_BLOCK_SIZE 56
Search WWH ::




Custom Search