Home >Backend Development >C++ >How to Calculate the MD5 Hash of a File in C using OpenSSL?
Calculating MD5 Hash from a File in C
In scenarios where safeguarding data integrity is critical, the MD5 hash algorithm plays a vital role. To compute the MD5 hash of a file in C , here's a robust implementation utilizing OpenSSL:
Implementation:
#include <fstream> #include <openssl/md5.h> int main() { // Open the file std::ifstream file("input_file.txt"); // Create a buffer to store the file contents std::vector<char> buffer(std::istreambuf_iterator<char>(file), {}); // Calculate the MD5 hash unsigned char hash[MD5_DIGEST_LENGTH]; MD5((unsigned char*) buffer.data(), buffer.size(), hash); // Convert the hash to a string std::stringstream ss; for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { ss << std::hex << std::setfill('0') << std::setw(2) << (int) hash[i]; } std::string md5_hash = ss.str(); // Print the MD5 hash std::cout << "MD5 hash: " << md5_hash << std::endl; return 0; }
This implementation opens the file, reads its contents into a buffer, and calculates the MD5 hash using the OpenSSL library. The hash is then converted to a hexadecimal string and displayed.
The above is the detailed content of How to Calculate the MD5 Hash of a File in C using OpenSSL?. For more information, please follow other related articles on the PHP Chinese website!