MD5 for iOS and Mac, the proper way

Thoughts | Tutorial By 4 years ago

There’s a lot of MD5 iOS solutions floating around out there. From the ones I’ve seen, they all have a common problem. They all assume you want to MD5 an NSData instance, meaning all of the data must be in memory in order to digest it.

Now this will work in most cases, but say you want to MD5 a 1 gigabyte file… on an iPhone. You’re probably going to have a few problems.

The correct solution for files on disk is to read them in chunk by chunk into a buffer, when you’re done processing the data in the buffer it gets cleared and then filled with the next bit of data from disk. This way you never load up more than the size of the buffer into memory.

I’ve been using my own MD5 methods for a long time now, which handle files on disk properly, as well as in memory data. I’ve just put the source onto GitHub for free use by anybody – it also supports md2, md4, sha1, sha224, sha256, sha384 and sha512.

[@"hello" md5];
[[NSData dataWithContentsOfFile:@"/file"] md5];
[NSString md5WithContentsOfFile:@"/file"];