c++ - 如何在 C++ 中获取文件的 MD5 哈希?

标签 c++ hash md5

我有文件路径。如何获取它的 MD5 哈希?

最佳答案

这是 md5sum 命令的直接实现,该命令计算并显示在命令行中指定的文件的 MD5。它需要链接到 OpenSSL 库 (gcc md5.c -o md5 -lssl) 才能工作。它是纯 C,但您应该能够轻松地将其适应您的 C++ 应用程序。

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <openssl/md5.h>

unsigned char result[MD5_DIGEST_LENGTH];

// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md) {
    int i;
    for(i=0; i <MD5_DIGEST_LENGTH; i++) {
            printf("%02x",md[i]);
    }
}

// Get the size of the file by its file descriptor
unsigned long get_size_by_fd(int fd) {
    struct stat statbuf;
    if(fstat(fd, &statbuf) < 0) exit(-1);
    return statbuf.st_size;
}

int main(int argc, char *argv[]) {
    int file_descript;
    unsigned long file_size;
    char* file_buffer;

    if(argc != 2) { 
            printf("Must specify the file\n");
            exit(-1);
    }
    printf("using file:\t%s\n", argv[1]);

    file_descript = open(argv[1], O_RDONLY);
    if(file_descript < 0) exit(-1);

    file_size = get_size_by_fd(file_descript);
    printf("file size:\t%lu\n", file_size);

    file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
    MD5((unsigned char*) file_buffer, file_size, result);
    munmap(file_buffer, file_size); 

    print_md5_sum(result);
    printf("  %s\n", argv[1]);

    return 0;
}

关于c++ - 如何在 C++ 中获取文件的 MD5 哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1220046/

相关文章:

python - 如何比较目录以确定哪些文件已更改?

Ruby 哈希错误 : undefined method [] when attempting to set deeply nested keys

javascript - JavaScript 中最快的 MD5 实现

c# - 将 md5 哈希字节数组转换为字符串

c++ - 我如何装饰谷歌测试夹具

C++ Money Class - 存储和四舍五入美分

c++ - OGRE不存在合适的转换函数

php - 您能向 PHP 人员解释 Perl 的哈希系统吗?

java - Android 上的 OpenGL : Any conflicts when calling OpenGL functions in both Java and C++?

php - 存储安全密码 MD5、BCRYPT、PBKDF2(PDO、MySQL、PHP)