libmhash计算md5值

2022-03-08  本文已影响0人  一路向后

1.源码实现

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

void reverse_bytes(unsigned char *start, unsigned long len)
{
    unsigned char *lo = start;
    unsigned char *hi = start + len - 1;
    unsigned char swap;

    while(lo<hi)
    {
        swap = *lo;
        *lo++ = *hi;
        *hi-- = swap;
    }
}

char *convert_to_hex(unsigned char *hash_data, unsigned long len)
{
    char *converted;
    unsigned long i;

    converted = (char *)malloc((len*2)+1);
    memset(converted, 0, (len*2)+1);

    for(i=0;i<len;i++)
    {
        sprintf(converted+(i*2), "%02x", hash_data[i]);
    }

    return converted;
}

char *hash(hashid hashType, unsigned char *data, unsigned long len)
{
    MHASH td;
    unsigned char *hash_data;
    char *converted=0;
    unsigned long block_size;

    if((td=mhash_init(hashType))==MHASH_FAILED)
        return 0;

    mhash(td, data, len);

    if((hash_data=(unsigned char *)mhash_end(td)))
    {
        block_size = mhash_get_block_size(hashType);
        if(hashType==MHASH_ADLER32)
            reverse_bytes(hash_data, block_size);
        converted = convert_to_hex(hash_data, block_size);
        mhash_free(hash_data);
    }

    return converted;
}

hashid get_hash_type_by_name(const char * name)
{
    if(strcasecmp(name, "crc32") == 0)
    {
        return MHASH_CRC32;
    }
    else if(strcasecmp(name, "md5") == 0)
    {
        return MHASH_MD5;
    }
    else if(strcasecmp(name, "ripemd160") == 0)
    {
        return MHASH_RIPEMD160;
    }

    return (hashid)-1;
}

int main()
{
    hashid type;
    char *hashed = 0;
    char data[128] = "hello world";
    char name[32] = "md5";
    int i;

    type = get_hash_type_by_name(name);

    if(type == -1)
    {
        return -1;
    }

    hashed = hash(type, (unsigned char *)data, strlen(data));

    if(!hashed)
    {
        return -1;
    }

    printf("%s\n", hashed);

    free(hashed);

    return 0;
}

2.编译源码

$ gcc -o test test.c -std=c89 -lmhash -Wl,-rpath=/usr/local/lib

3.运行及其结果

$ ./test
5eb63bbbe01eeed093cb22bb8f5acdc3
上一篇下一篇

猜你喜欢

热点阅读