网上有 md5.c , md5.h, 但是里面只有 MD5Init(), MD5Update(), MD5Final() 三个函数,
只可以直接对字符进行操作, 而没有直接求文件md5的接口. 以下是我的实现, 可计算32位和16位的md5值.
/*****************************************************************************
* Copyright : All Rights Reserved.
*
* Date : 2012-09-15 22:37:49
* Author/Corporation : Dengzhaoqun
* Email : dengzhaoqun@163.com
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "md5.h"
char *MD5_file (char *path, int md5_len)
{
FILE *fp = fopen (path, "rb");
MD5_CTX mdContext;
int bytes;
unsigned char data[1024];
char *file_md5;
int i;
if (fp == NULL) {
fprintf (stderr, "fopen %s failed\n", path);
return NULL;
}
MD5Init (&mdContext);
while ((bytes = fread (data, 1, 1024, fp)) != 0)
{
MD5Update (&mdContext, data, bytes);
}
MD5Final (&mdContext);
file_md5 = (char *)malloc((md5_len + 1) * sizeof(char));
if(file_md5 == NULL)
{
fprintf(stderr, "malloc failed.\n");
return NULL;
}
memset(file_md5, 0, (md5_len + 1));
if(md5_len == 16)
{
for(i=4; i<12; i++)
{
sprintf(&file_md5[(i-4)*2], "%02x", mdContext.digest[i]);
}
}
else if(md5_len == 32)
{
for(i=0; i<16; i++)
{
sprintf(&file_md5[i*2], "%02x", mdContext.digest[i]);
}
}
else
{
fclose(fp);
free(file_md5);
return NULL;
}
fclose (fp);
return file_md5;
}
int main(int argc, char *argv[])
{
char *md5;
md5 = MD5_file("temp", 16);
printf("16: %s\n", md5);
free(md5);
md5 = MD5_file("temp", 32);
printf("32: %s\n", md5);
free(md5);
return 0;
}
以下是 md5.c的源码
#include "md5.h"
/*
**********************************************************************
** md5.c **
** RSA Data Security, Inc. MD5 Message Digest Algorithm **
** Created: 2/17/90 RLR **
** Revised: 1/91 SRD,AJ,BSK,JT Reference C Version **
**********************************************************************
*/
/*
**********************************************************************
** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **
** **
** License to copy and use this software is granted provided that **
** it is identified as the "RSA Data Security, Inc. MD5 Message **
** Digest Algorithm" in all material mentioning or referencing this **
** software or this function. **
** **
** License is also granted to make and use derivative works **
** provided that such works are identified as "derived from the RSA **
** Data Se