代码
#include <stdio.h>
#include <openssl/md5.h>std::string get_file_md5(const char *path){unsigned char digest [MD5_DIGEST_LENGTH];std::ifstream file(path, std::ios::in | std::ios::binary); //打开文件MD5_CTX md5_ctx;MD5_Init(&md5_ctx);char data_Buff[1024];while (!file.eof()) {file.read(data_Buff, 1024); //读取文件int length = file.gcount();if (length) {MD5_Update(&md5_ctx, data_Buff, length); //将当前文件加入并且更新MD5}}MD5_Final(digest, &md5_ctx); //获取MD5//coutchar mdString[33];for(int i = 0; i < 16; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("md5 digest: %s\n", mdString);
}
#include <stdio.h>
#include <openssl/md5.h>int main()
{unsigned char c[MD5_DIGEST_LENGTH];char *filename="file.c";int i;FILE *inFile = fopen (filename, "rb");MD5_CTX mdContext;int bytes;unsigned char data[1024];if (inFile == NULL) {printf ("%s can't be opened.\n", filename);return 0;}MD5_Init (&mdContext);while ((bytes = fread (data, 1, 1024, inFile)) != 0)MD5_Update (&mdContext, data, bytes);MD5_Final (c,&mdContext);for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", c[i]);printf (" %s\n", filename);fclose (inFile);return 0;
}
参考链接
- openssl md5 and sha
- md5sum
- How to calculate the MD5 hash of a large file in C?