Let’s jump straight into the code:

#import <CommonCrypto/CommonDigest.h>

NSString* MD5StringOfString(NSString* inputStr)
	NSData* inputData = [inputStr dataUsingEncoding:NSUTF8StringEncoding];
	unsigned char outputData[CC_MD5_DIGEST_LENGTH];
	CC_MD5([inputData bytes], [inputData length], outputData);
	NSMutableString* hashStr = [NSMutableString string];
	int i = 0;
	for (i = 0; i < CC_MD5_DIGEST_LENGTH; ++i)
		[hashStr appendFormat:@"%02x", outputData[i]];
	return hashStr;

Now for the explanation.

First, the input string is encoded into UTF8 data so that the hash comes out the same as an ASCII string hash, unless there are non-ASCII characters in the string.

Next, the CC_MD5 function creates the 16 byte MD5 hash. CC_MD5 is a function from CommonCrypto, which is part of the Foundation framework for Mac and iPhone. Because you will already be using the Foundation framework, you don’t need to link against any additional libraries or frameworks.

Finally, the 16 byte hash is converted to a 32 character hexadecimal string; the most commonly used format.

Here is how the function is used:

NSString* inputStr = @"test";
NSLog(@"The MD5 hash of \"%@\" is %@", inputStr, MD5StringOfString(inputStr));
//outputs: The MD5 hash of "test" is 098f6bcd4621d373cade4e832627b4f6

You may even want to wrap the hashes in a hash class.

A word of caution: if the hash is generated from sensitive information such as passwords, then you should be aware of hashes weakness to precomputation attacks. Make sure you sprinkle some salt first.

  • Gordon

    Thank you. I’ve been scratching my head for a while about this and of all the examples I looked at yours was the easiest to understand.