MD5 - Simple Implementation

Simple Implementation

A simple MD5 implementation in C, that follows the pseudocode:

/* * Simple MD5 implementation * * Compile with: gcc -o md5 -O3 -lm md5.c */ #include #include #include #include // leftrotate function definition #define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c)))) // These vars will contain the hash uint32_t h0, h1, h2, h3; void md5(uint8_t *initial_msg, size_t initial_len) { // Message (to prepare) uint8_t *msg = NULL; // Note: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating // r specifies the per-round shift amounts uint32_t r = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; // Use binary integer part of the sines of integers (in radians) as constants// Initialize variables: h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; // Pre-processing: adding a single 1 bit //append "1" bit to message /* Notice: the input bytes are considered as bits strings, where the first bit is the most significant bit of the byte. */ // Pre-processing: padding with zeros //append "0" bit until message length in bit ≡ 448 (mod 512) //append length mod (2 pow 64) to message int new_len; for(new_len = initial_len*8 + 1; new_len%512!=448; new_len++); new_len /= 8; msg = calloc(new_len + 64, 1); // also appends "0" bits // (we alloc also 64 extra bytes...) memcpy(msg, initial_msg, initial_len); msg = 128; // write the "1" bit uint32_t bits_len = 8*initial_len; // note, we append the len memcpy(msg + new_len, &bits_len, 4); // in bits at the end of the buffer // Process the message in successive 512-bit chunks: //for each 512-bit chunk of message: int offset; for(offset=0; offsetThe message to hash is passed via the first argument of the command line.

Read more about this topic:  MD5

Famous quotes containing the word simple:

    A superstition which pretends to be scientific creates a much greater confusion of thought than one which contents itself with simple popular practices.
    Johan Huizinga (1872–1945)