Skip to content

Instantly share code, notes, and snippets.

@kwharrigan
Created April 15, 2012 03:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwharrigan/2389719 to your computer and use it in GitHub Desktop.
Save kwharrigan/2389719 to your computer and use it in GitHub Desktop.
Use openssl to produce an md5 hash of a file
#include <openssl/md5.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char**argv)
{
FILE *fh;
long filesize;
unsigned char *buf;
unsigned char *md5_result = NULL;
int i;
if (argc < 2)
{
printf("Usage: md5_test <filename>\n");
return 1;
}
fh = fopen(argv[1], "r");
fseek(fh, 0L, SEEK_END);
filesize = ftell(fh);
fseek(fh, 0L, SEEK_SET);
buf = malloc(filesize);
fread(buf, filesize, 1, fh);
fclose(fh);
md5_result = malloc(MD5_DIGEST_LENGTH);
MD5(buf, filesize, md5_result);
printf("MD5 (%s) = ", argv[1]);
for (i=0; i < MD5_DIGEST_LENGTH; i++)
{
printf("%02x", md5_result[i]);
}
printf("\n");
free(md5_result);
free(buf);
return 0;
}
@kwharrigan
Copy link
Author

According to the man-page, it is bad practice to write it like this but I just did it for fun...

Applications should use the higher level functions EVP_DigestInit(3)
 etc. instead of calling the hash functions directly."

Make sense... why write hash-dependent code when you can make it generic?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment