Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the MD5 hash of a file in C++? [closed]

Tags:

c++

hash

md5

I've the file path. How can I get the MD5 hash of it?

like image 564
user145586 Avatar asked Aug 02 '09 22:08

user145586


People also ask

How do I find the MD5 hash of a hidden file?

Open a terminal window. Type the following command: md5sum [type file name with extension here] [path of the file] -- NOTE: You can also drag the file to the terminal window instead of typing the full path. Hit the Enter key. You'll see the MD5 sum of the file.

Can you reverse MD5 hash?

No, it is not possible to reverse a hash function such as MD5: given the output hash value it is impossible to find the input message unless enough information about the input message is known.

Can MD5 be broken?

The MD5 message-digest algorithm is a cryptographically broken but still widely used hash function producing a 128-bit hash value. Although MD5 was initially designed to be used as a cryptographic hash function, it has been found to suffer from extensive vulnerabilities.


1 Answers

Here's a straight forward implementation of the md5sum command that computes and displays the MD5 of the file specified on the command-line. It needs to be linked against the OpenSSL library (gcc md5.c -o md5 -lssl) to work. It's pure C, but you should be able to adapt it to your C++ application easily enough.

#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; } 
like image 106
D'Nabre Avatar answered Oct 06 '22 00:10

D'Nabre