Home | Developer Blog

Tidbit - Calculating file checksums

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.

Stopwatch timing in Cocoa

Sometimes you want to time things in your code. The usual pattern is to store the current time, do something, store the current time, compute the difference, and then convert it to something useful, like seconds elapsed. That pattern gets old fast, so here’s a little Cocoa stopwatch class that neatly encapsulates stopwatch timing on Mac OS X.

Read More…