#include #include /* md5sum */ #include #include #include #include /** * Get the size of the file by its file descriptor * * @param file_descript */ unsigned long get_size_by_fd(int fd) { struct stat statbuf; if (fstat(fd, &statbuf) < 0) { exit(EXIT_FAILURE); } return statbuf.st_size; } /** * Print the MD5 sum as hex-digits. * * @param MD5 checksum */ void print_md5_sum(unsigned char* md5) { for (unsigned int i = 0; i < MD5_DIGEST_LENGTH; i++) { printf("%02x", md5[i]); } } /** * Converts MD5 checksum to hex. * * @param MD5 checksum */ std::string to_hex(unsigned char* md5) { static const char digits[] = "0123456789abcdef"; std::string result; for (unsigned int i = 0; i < MD5_DIGEST_LENGTH; i++) { result += digits[md5[i] / MD5_DIGEST_LENGTH]; result += digits[md5[i] % MD5_DIGEST_LENGTH]; } return result; } /** * Computes a MD5 checksum and compares it to its corresponding calibrated checksum. * * @param File path to compute checksum, corresponding calibrated checksum */ void md5sum(std::string file_path, unsigned char md5[MD5_DIGEST_LENGTH]) { /* * Variable initialisation */ int file_descript; unsigned long file_size; unsigned char* file_buffer; /* Checks if the file path can be opened. */ file_descript = open(file_path.c_str(), O_RDONLY); if (file_descript < 0) { std::cerr << "Unable to open " << file_path << std::endl; exit(EXIT_FAILURE); } /* Grabs the size of file */ file_size = get_size_by_fd(file_descript); /* Generates the buffer */ file_buffer = (unsigned char*) mmap((caddr_t)0, file_size, PROT_READ, MAP_SHARED, file_descript, 0); /* Computes the MD5 checksum to result */ MD5(file_buffer, file_size, md5); /* Removes fime_buffer and file_size */ munmap(file_buffer, file_size); }