Tutorial: How To Calculate MD5 or SHA Hash Of File Efficiently

Calculating an MD5 hash is a fairly simple task using the CommonCrypto library, which I mentioned previously in an article on getting Gravatars which involved calculating the MD5 hash of a user’s e-mail.

While it is easy to do these calculations with CommonCrypto it is extremely inefficient to do so with the commonly used high level NSFileHandle commands.  Unfortunately, the problem with this solution is that it makes very inefficient use of memory because NSFileHandle returns an autorelease object making it impractical for large files.  One solution to this is to use the CFReadStream.

With this solution you can keep the memory usage low while reading in very large files.

You can read a more in depth tutorial on this topic here:
Compute MD5 Or SHA Hash Efficiently On iOS

A Github project has also been created to make this solution more straightforward:
http://github.com/Fuitad/FileMD5Hash

If you’re in a situation where you need to calculate the MD5 hash of a file, and are running into memory problems this should help.

Thanks for reading, please share this using the buttons below!

©2010 iPhone, iOS 4, iPad SDK Development Tutorial and Programming Tips. All Rights Reserved.

.

Share and Enjoy:

RSS
Twitter
Facebook
DZone
HackerNews
del.icio.us
FriendFeed

Leave a Reply

Your email address will not be published. Required fields are marked *