C program to verify the integrity of a file with md5 checksum

Most of the times we downloaded some files from the internet, and we also see people provides md5sum along with the link to download. the md5sum provided is given for us to make sure, once we download the complete files, and do md5sum on our downloaded file, it should match with the md5sum provided for us. This is verify that we have downloaded complete file and there has been no break into the downloaded file.

If by any reason like network error, we are unable to download complete file then md5sum we calculated and md5sum provided will not match, so we can conclude that our downloaded file is corrupted and we needs to download again.

Following is the C program which calculates the md5sum of a file, and check whether it matches with the predefined md5sum.

for our testing purpose, we will create a “helloworld.txt” and use the same to calculate md5, you need to use your own filename or enhance below code to read filename from command line.

 $ echo "This is helloworld"  > helloworld.txt 
 $  vim md5-calculate.c 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>

char * calculate_file_md5(const char *filename) {
	unsigned char c[MD5_DIGEST_LENGTH];
	int i;
	MD5_CTX mdContext;
	int bytes;
	unsigned char data[1024];
	char *filemd5 = (char*) malloc(33 *sizeof(char));

	FILE *inFile = fopen (filename, "rb");
	if (inFile == NULL) {
		perror(filename);
		return 0;
	}

	MD5_Init (&mdContext);

	while ((bytes = fread (data, 1, 1024, inFile)) != 0)

	MD5_Update (&mdContext, data, bytes);

	MD5_Final (c,&mdContext);

	for(i = 0; i < MD5_DIGEST_LENGTH; i++) {
		sprintf(&filemd5[i*2], "%02x", (unsigned int)c[i]);
	}

	printf("calculated md5:%s ", filemd5);
	printf (" %s\n", filename);
	fclose (inFile);
	return filemd5;
}

int main(int argc, char **argv) {
	char * predefined_md5 = "8e2745d333daa9666a8bbebcd32a39bb";
	char *new_md5 = calculate_file_md5("helloworld.txt");

        if (!strcmp(predefined_md5, new_md5)) {
                printf("md5 matched\n");
        } else {
                printf("md5 not matched\n");
        }
	free(new_md5);
	return 0;
}
 $ gcc -o md5-calculate  md5-calculate.c -lcrypto 
$ ./md5-calculate 
calculated md5:8e2745d333daa9666a8bbebcd32a39bb  helloworld.txt
md5 matched

Leave a Comment