产看文件的md5值
头文件
#ifndef OPENSSL_MD5_H
#define OPENSSL_MD5_H
#define INPUT_BUFFER_SIZE 100 * 1024
int getMd5Str(const char* data, int length, char* result, int byteSize = 32);
int getMd5File(const char* filePath, char* result, int byteSize = 32);
#endif
执行文件
#include "openssl_md5.h"
#include <openssl/md5.h>
#include <stdio.h>
#include "string.h"
/**
* @brief Get the Md5 Str object
* 返回32位的MD5
* @param data My Param doc
* @param length strlen(data)
* @param result 返回MD5值,空间要大于33
* @return int
*/
int getMd5Str(const char* data, int length, char* result, int byteSize)
{
MD5_CTX c;
MD5_Init(&c);
MD5_Update(&c, data, length);
unsigned char digest[16] = { 0 };
char hexBuffer[3];
MD5_Final(digest, &c);
result[0] = '\0';
for (size_t i = 0; i != 16; ++i)
{
if (digest[i] < 16) sprintf(hexBuffer, "0%x", digest[i]);
else sprintf(hexBuffer, "%x", digest[i]);
strcat(result, hexBuffer);
}
result[32] = '\0';
if(byteSize == 16)
{
char temp[17];
// 如果格式化后的字符串长度大于等于 size,超过 size 的部分会被截断,只将其中的 (size-1) 个字符复制到 str 中,并给其后添加一个字符串结束符 \0,返回值为欲写入的字符串长度。
snprintf(temp, 17, "%s", result + 8);
temp[16] = '\0';
sprintf(result, "%s", temp);
}
return 0;
}
int getMd5File(const char* filePath, char* result, int byteSize)
{
FILE *file = fopen(filePath, "rb");
if (file)
{
MD5_CTX c;
MD5_Init(&c);
char buffer[INPUT_BUFFER_SIZE];
while (!feof(file))
{
size_t numberOfObjects = fread(buffer, sizeof(char), INPUT_BUFFER_SIZE, file);
MD5_Update(&c, buffer, numberOfObjects);
}
fclose(file);
unsigned char digest[16] = { 0 };
char hexBuffer[3];
MD5_Final(digest, &c);
result[0] = '\0';
for (size_t i = 0; i != 16; ++i)
{
if (digest[i] < 16) sprintf(hexBuffer, "0%x", digest[i]);
else sprintf(hexBuffer, "%x", digest[i]);
strcat(result, hexBuffer);
}
result[32] = '\0';
if(byteSize == 16)
{
char temp[17];
snprintf(temp, 17, "%s", result + 8);
temp[16] = '\0';
sprintf(result, "%s", temp);
}
}
else
{
return 1;
}
return 0;
}
测试程序
#include <string.h>
#include "openssl_md5.h"
#include "stdio.h"
int main()
{
char result[32];
char *data = "All is well!";
getMd5Str(data, strlen(data), result);
printf("%s\n", result);
getMd5Str(data, strlen(data), result, 16);
printf("%s\n", result);
getMd5File("src.zip", result);
printf("%s\n", result);
getMd5File("src.zip", result, 16);
printf("%s\n", result);
return 0;
}