Tidbit - Calculating file checksums
13-Jul-08
I’m going to start posting what I’m calling tidbits - morsel sized pieces of code for common tasks on Mac OS X.
The first of these is computing a file checksum (MD5 to be precise). Apple provides the functionality in CommonCrypto/CommonDigest.h. This uses routines in libSystem and avoids loading the entire of OpenSSL to simply compute a checksum. The code is really simple:
#include <CommonCrypto/CommonDigest.h> NSString* fileName = @"PATHTOFILE"; unsigned char md5[16]; NSData* data = [NSData dataWithContentsOfFile:fileName]; CC_MD5([data bytes], [data length], md5); // md5 now contains the md5 digest for the file contents
Trivially easy. The CommonDigest.h header contains functions for MD2, MD4, MD5, and SHA1.