Home > Article > Backend Development > How do I Calculate the MD5 Hash of a File in C ?
Getting MD5 Hash from File in C : A Step-by-Step Guide
In C , computing the MD5 hash of a file is a crucial task for data integrity verification and secure transmission. To simplify this process, let's dive into a practical implementation.
Step 1: Link to OpenSSL Library
For this implementation, you'll need the OpenSSL library, which provides the MD5 hash algorithm. Use the following line during compilation:
gcc md5.c -o md5 -lssl
Step 2: Define the MD5 Hash
Declare an array to store the MD5 hash value:
unsigned char result[MD5_DIGEST_LENGTH];
Step 3: Open the File and Get Its Size
int file_descript = open(argv[1], O_RDONLY); unsigned long file_size = get_size_by_fd(file_descript);
Step 4: Map the File into Memory
To efficiently process large files, map the file contents into memory using mmap():
file_buffer = mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
Step 5: Compute the MD5 Hash
Use the MD5() function to compute the hash value of the mapped file buffer:
MD5((unsigned char*) file_buffer, file_size, result);
Step 6: Print the MD5 Hash
Display the computed MD5 hash as hexadecimal digits:
print_md5_sum(result); printf(" %s\n", argv[1]);
Complete Code Snippet:
#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]; void print_md5_sum(unsigned char* md){ ... } unsigned long get_size_by_fd(int fd){ ... } int main(int argc, char *argv[]){ ... }
This code gives you a comprehensive implementation to calculate the MD5 hash of files in C .
The above is the detailed content of How do I Calculate the MD5 Hash of a File in C ?. For more information, please follow other related articles on the PHP Chinese website!