md5_test.cpp
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
bool funFileMD5SUM(char* lpcstrFilePath, char *pbymd5Buff)
{
bool bRet = false;
unsigned char achbyBuff[17] = {0};
unsigned char *pbyBuff = achbyBuff;
FILE *inFile = fopen (lpcstrFilePath, "rb");
MD5_CTX mdContext;
int bytes;
unsigned char data[1024];
if (inFile == NULL) {
printf( "%s can't be opened.\n", lpcstrFilePath);
return bRet;
}
MD5_Init (&mdContext);
while ((bytes = fread (data, 1, 1024, inFile)) != 0)
MD5_Update (&mdContext, data, bytes);
MD5_Final (pbyBuff,&mdContext);
char szBuf[1024] = {0};
for(int i = 0; i < MD5_DIGEST_LENGTH; i++)
{
sprintf(&szBuf[i*2], "%02x", pbyBuff[i]);
}
strcpy((char*)pbymd5Buff, (char*)szBuf);
strcat(szBuf, " ");
strcat(szBuf, lpcstrFilePath);
printf( "md5sum %d %s\n", MD5_DIGEST_LENGTH, szBuf);
fclose (inFile);
bRet = true;
return bRet;
}
bool funStrMD5SUM(char* lpcstrFilePath,int bytes, char* pbymd5Buff)
{
bool bRet = false;
unsigned char achbyBuff[17] = {0};
unsigned char *pbyBuff = achbyBuff;
MD5_CTX mdContext;
unsigned char data[1024];
MD5_Init (&mdContext);
MD5_Update (&mdContext, lpcstrFilePath, bytes);
MD5_Final (pbyBuff,&mdContext);
char szBuf[1024] = {0};
for(int i = 0; i < MD5_DIGEST_LENGTH; i++)
{
sprintf(&szBuf[i*2], "%02x", pbyBuff[i]);
}
strcpy((char*)pbymd5Buff, (char*)szBuf);
strcat(szBuf, " ");
strcat(szBuf, lpcstrFilePath);
printf( "md5sum %d %s\n", MD5_DIGEST_LENGTH, szBuf);
bRet = true;
return bRet;
}
int main(int argc, char* argv[])
{
char achMd5[100]= {0};
funStrMD5SUM((char*)"hello", 5, achMd5);
memset(achMd5,0, sizeof(achMd5));
funFileMD5SUM((char*)"./md5_test.cpp",achMd5);
return 0;
}
编译:
# g++ -o md5_test md5_test.cpp -l crypto
运行结果:
# ./md5_test
md5sum 16 5d41402abc4b2a76b9719d911017c592 hello
md5sum 16 7ac513537aefbdf102546e077371b78c ./md5_test.cpp
执行shell命令查看结果是否正确:
# echo -n "hello" | md5sum
5d41402abc4b2a76b9719d911017c592 -
# md5sum ./md5_test.cpp
7ac513537aefbdf102546e077371b78c ./md5_test.cpp
注意:编译的时候要加上库连接,否则会出现下面的报错:
# g++ -o md5_test md5_test.cpp
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /tmp/cc4EOdWl.o: in function `funFileMD5SUM(char*, char*)':
md5_test.cpp:(.text+0x85): undefined reference to `MD5_Init'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: md5_test.cpp:(.text+0xd2): undefined reference to `MD5_Update'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: md5_test.cpp:(.text+0xea): undefined reference to `MD5_Final'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /tmp/cc4EOdWl.o: in function `funStrMD5SUM(char*, int, char*)':
md5_test.cpp:(.text+0x24f): undefined reference to `MD5_Init'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: md5_test.cpp:(.text+0x271): undefined reference to `MD5_Update'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: md5_test.cpp:(.text+0x287): undefined reference to `MD5_Final'
collect2: error: ld returned 1 exit status