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.
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.1609238088130951, "perplexity": 4180.454006834181}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2014-10/segments/1393999651159/warc/CC-MAIN-20140305060731-00079-ip-10-183-142-35.ec2.internal.warc.gz"}