/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TestMd5 // // Test MD5 algorithm against test vectors /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static bool TestMd5 ( void ) { int i; int k; int len; Md5Context context; MD5_HASH hash; bool success = true; for( i=0; i<NUM_TEST_VECTORS; i++ ) { Md5Initialise( &context ); len = (int) gTestVectors[i].PlainTextSize ? gTestVectors[i].PlainTextSize : (int)strlen( gTestVectors[i].PlainText ); Md5Update( &context, gTestVectors[i].PlainText, (uint32_t)len ); Md5Finalise( &context, &hash ); if( memcmp( &hash, &gTestVectors[i].Md5Hash, sizeof(hash) ) == 0 ) { // Test vector passed } else { printf( "TestMd5 - Test vector %u failed\n", i ); success = false; } } // Check the vectors again, this time adding just 1 char at a time to the hash functions for( i=0; i<NUM_TEST_VECTORS; i++ ) { Md5Initialise( &context ); len = (int) gTestVectors[i].PlainTextSize ? gTestVectors[i].PlainTextSize : (int)strlen( gTestVectors[i].PlainText ); for( k=0; k<len; k++ ) { Md5Update( &context, &gTestVectors[i].PlainText[k], 1 ); } Md5Finalise( &context, &hash ); if( memcmp( &hash, &gTestVectors[i].Md5Hash, sizeof(hash) ) == 0 ) { // Test vector passed } else { printf( "TestMd5 - Test vector %u failed [byte by byte]\n", i ); success = false; } } return success; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // main // // Program entry point //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main ( int ArgC, char** ArgV ) { char* string; Md5Context md5Context; MD5_HASH md5Hash; uint16_t i; if( 2 != ArgC ) { printf( "Syntax\n" " Md5String <String>\n" ); return 1; } string = ArgV[1]; Md5Initialise( &md5Context ); Md5Update( &md5Context, string, (uint32_t)strlen(string) ); Md5Finalise( &md5Context, &md5Hash ); for( i=0; i<sizeof(md5Hash); i++ ) { printf( "0x%2.2x,", md5Hash.bytes[i] ); } printf( "\n" ); return 0; }
sg_md5_ctx *sg_md5_start(void) { Md5Context *ctx; ctx = (Md5Context *)malloc(sizeof(Md5Context)); if (!ctx) return NULL; Md5Initialise(ctx); return ctx; }
int md5str(char *buffer, char *target) { Md5Context md5Context; MD5_HASH md5Hash; uint16_t i; Md5Initialise( &md5Context ); Md5Update( &md5Context, buffer, (uint32_t)strlen(buffer) ); Md5Finalise( &md5Context, &md5Hash ); for( i=0; i<sizeof(md5Hash); i++ ) { sprintf( target+i*2, "%02x", md5Hash.bytes[i] ); } return 0; }
struct sg_md5_hash sg_md5_easy_buf(void *buf, size_t len, enum sg_md5_fmt fmt) { Md5Context ctx; MD5_HASH hash; struct sg_md5_hash res; assert(buf); assert(len > 0); ZERO(hash, sizeof(struct sg_md5_hash)); Md5Initialise(&ctx); Md5Update(&ctx, buf, (uint32_t)len); Md5Finalise(&ctx, &hash); md5_hash_fmt(&hash, &res, fmt); return res; }