Home >Backend Development >C++ >How to Calculate an MD5 Hash from a File in C ?

How to Calculate an MD5 Hash from a File in C ?

DDD
DDDOriginal
2024-11-12 14:50:02754browse

How to Calculate an MD5 Hash from a File in C  ?

Calculating MD5 Hash from Files in C

Getting the MD5 hash of a file in C is essential for data security and integrity checks. In this article, we'll explore a straightforward C implementation that can compute and display the MD5 hash of a file.

The implementation leverages the OpenSSL library to perform the MD5 calculations. It includes functions for:

  • Reading a file into a buffer
  • Using the MD5 function to calculate the hash
  • Printing the result as hex-digits

The code starts by opening the specified file and mapping it into memory using mmap(). This allows the application to work with the file as a buffer in memory, facilitating efficient MD5 computation. The MD5() function then calculates the hash and stores it in a predefined array.

Finally, the print_md5_sum() function converts the MD5 hash into hex-digits and prints them alongside the file name. This allows for easy verification and comparison of file integrity.

Here's the code:

#include <openssl/md5.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
}

The above is the detailed content of How to Calculate an MD5 Hash from a File in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn