1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
// 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;
}
// Print the MD5 sum as hex-digits.
void print_md5_sum(unsigned char* md)
{
for (unsigned int i = 0; i < MD5_DIGEST_LENGTH; i++)
{
printf("%02x", md[i]);
}
}
int md5sum_check(std::string filepath, const char* HASH)
{
unsigned char result[MD5_DIGEST_LENGTH];
int file_descript;
unsigned long file_size;
char* file_buffer;
file_descript = open(filepath.c_str(), O_RDONLY);
if (file_descript < 0)
{
std::cerr << "Unable to open " << filepath << std::endl;
return 1;
}
file_size = get_size_by_fd(file_descript);
file_buffer = static_cast<char*>(mmap((caddr_t)0, file_size, PROT_READ, MAP_SHARED, file_descript, 0));
MD5((unsigned char*) file_buffer, file_size, result);
munmap(file_buffer, file_size);
void* c = memchr(result, '\0', MD5_DIGEST_LENGTH);
printf("%c\n", c);
/*
* 1. Checks if there's any difference between the two hashes
* 2. Checks if hash is null-terminated
*/
if ((memcmp(result, HASH, MD5_DIGEST_LENGTH) != 0) && (c != NULL))
{
print_md5_sum(result);
std::cerr << " != " << HASH << "\n" << filepath << " is not calibrated!" << std::endl;
return 0;
}
print_md5_sum(result);
std::cout << " = " << HASH << "\n"<< filepath << " is calibrated." << std::endl;
return 0;
}
|