humblebeast
humblebeast

Reputation: 303

Debugging Hashed Results: Lengths, Arrays, Chars

Do these results make sense?

I am trying to understand how mhash works, but does anyone know how these results make sense??

mac is a char, and based on strlen its length is 16 however, this sample program provided by mhash outputs the following hash which is in hexadecimal format (.x) 750c783e6ab0b503eaa86e310a5db738 And the length of this mac[i] is twice the size of 16, anyone have any idea on why this might be?

// output result
// 0x750c783e6ab0b503eaa86e310a5db738 (MD5) (32)
// mac length: 16
// md5 length: 16

#include <mhash.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char password[] = "Jefe";
    int keylen = 4;
    char data[] = "what do ya want for nothing?";
    int datalen = 28;

    MHASH td;
    unsigned char *mac;
    int i, j;

    td = mhash_hmac_init(MHASH_MD5, password, keylen, mhash_get_hash_pblock(MHASH_MD5));

    mhash(td, data, datalen);
    mac = mhash_hmac_end(td);

    int md5len = mhash_get_block_size(MHASH_MD5);

    printf("0x");
    for (i = 0; i < md5len; i++)
    {
        printf("%.2x", mac[i]);
    }
    printf("\n");

    // I don't understand how the mac is a different size than the version printed out!?
    printf("%x\n", mac);

    int maclen = strlen(mac);
    printf("mac length: %d\n", maclen);
    printf("md5 length: %d\n", md5len);

    exit(0);
}

Also, if I try to output mac using printf like the following:

printf("%x\n", mac);

I would get this:

u
 x>j����n1
]�8

The API for mhash can be found here: http://mhash.sourceforge.net/mhash.3.html

Thanks for your help in advance

Upvotes: 1

Views: 44

Answers (1)

rslemos
rslemos

Reputation: 2730

Don't take mac as a string (either as array of char or pointer to first char of a string).

mac is to be read as an array of bytes, whose size is known in advance (the result of mhash_get_block_size).

strlen(mac) is undefined. Only by chance you'll get the right size (think of a hash that happens to have a zero byte: it will end the wanna-be-string prematurely).

Upvotes: 1

Related Questions