Create MD5 Hash from NSString, NSData or a File

February 28, 2011

MD5 (Message-Digest algorithm 5) is a crytographic hash function that is commonly used as a means to verify file integrity. For instance, if you store a file on a server and download the same onto a device, you can compare the server hosted MD5 value to a received copy to verify the file was downloaded intact. An MD5 hash is commonly shown as a 32-digit hex value.

In this post I’ll create two Objective-C Categories, extending NSString and NSSData classes to provide MD5 conversion method for strings and byte buffers, respectively. The beauty of working with Categories is that all NSString and NSData objects will have access to the MD5 methods. To learn more about working with Categories, head over to this post: Categories Explained.

NSString and MD5

Let’s start by creating the interface definition for the category:

@interface NSString(MD5)
 
- (NSString *)MD5;
 
@end

Save this code into a file with the name NSString+MD5.h The comments in the code explains how to convert a string to MD5 and a corresponding hex string value.

NSString MD5 Implementation

The implementation of the MD5 algorithm is below. Save the code in a file with the name NSString+MD5.m

#import <CommonCrypto/CommonDigest.h>
 
@implementation NSString(MD5)
 
- (NSString*)MD5
{
  // Create pointer to the string as UTF8
  const char *ptr = [self UTF8String];
 
  // Create byte array of unsigned chars
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
 
  // Create 16 byte MD5 hash value, store in buffer
  CC_MD5(ptr, strlen(ptr), md5Buffer);
 
  // Convert MD5 value in the buffer to NSString of hex values
  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) 
    [output appendFormat:@"%02x",md5Buffer[i]];
 
  return output;
}
Generating MD5 Hash on NSString

The code below shows how to call the new MD5 method on an NSString object:

#import "NSString+MD5.h"
 
...
 
NSString *str = @"String to convert to MD5";
 
// Convert and print the MD5 value to the console
NSLog(@"%@", [str MD5]);

Below we follow a similar process, this time working with NSData to add an MD5 method. The code for the NSData object will come from the contents of a file, this will provide the background you need to generate an MD5 from a file or an NSData object that you could populate via other means such as the return value from a NSURLConnection.

NSData and MD5

Create the interface definition for the NSData class:

@interface NSData(MD5)
 
- (NSString *)MD5;
 
@end

Save the code in a file: NSData+MD5.h

NSData MD5 Implementation

The MD5 algorithm for working with the NSData byte buffer is below. Save the code in a file: NSData+MD5.m

#import <CommonCrypto/CommonDigest.h>
 
@implementation NSData(MD5)
 
- (NSString*)MD5
{
  // Create byte array of unsigned chars
  unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
 
  // Create 16 byte MD5 hash value, store in buffer
  CC_MD5(self.bytes, self.length, md5Buffer);
 
  // Convert unsigned char buffer to NSString of hex values
  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) 
    [output appendFormat:@"%02x",md5Buffer[i]];
 
  return output;
}
 
@end
Generating MD5 Hash on NSData or a File

The code below will create a NSData object from a file and convert the byte values to an MD5 hash.

#import "NSData+MD5.h"
 
...
 
NSString *path = [[NSBundle mainBundle] pathForResource:@"TestFile" ofType:@"txt"];  
NSData *nsData = [NSData dataWithContentsOfFile:path];  
if (nsData) 
  NSLog(@"%@", [nsData MD5]);
iPhone MD5 Xcode Project

The Xcode project attached includes working examples of creating MD5 hash values from both a string and a file. To verify all is working as expected, the output to the console for each MD5 value should be the same, as the contents of the file TestFile.txt is the equivalent to the NSString value – view the source and TestFile.txt and this will all make more sense.

Download iPhone MD5 Xcode Project

Export Control

From what I’ve been able to find, MD5 is not subject to the same export controls as encryption. This article states the following: “… MD-5, N-HASH, and SHS are ‘hashing routines’ that perform a data authentication function and, by themselves, are not controlled for export under the ITAR because cryptographic software that is solely limited to a data authentication function is excluded from Category XIII(b) of the United States Munitions List. See 22 C.F.R. Section 121.1 XIII(b)(vi).”

Here is another reference Guide to Web Authentication Alternatives, which states: “It was one of the goals of the team that designed digest authentication to devise a protocol whose use would not be limited by copyright or export restrictions. That’s why digest authentication does not use two-way encryption algorithms, but only one-way MD5 encryption. The US export regulations explicitly did not restrict export of such programs.”

However, before using MD5 with an application that will be exported, please do your own research to validate that MD5 is not subject to export controls.

11 comments

I like that! Very nice.

This wouldn’t be classified as encryption thus needing export check with US gov?

by Lee Armstrong on Feb 28, 2011. Reply #

Thanks for the question on this. I’ve updated the post to include information about Export Control, based on my understanding. However, please do verify this information to make sure things haven’t changed since the articles mentioned (links) were published.

by John Muchow on Feb 28, 2011. Reply #

Thank you John, Now I can finally write MD5 checks to that Awsome custom backup machine I’ve always wanted to make.

by Luke on Mar 16, 2011. Reply #

Thanks, very helpful

by daniela on May 6, 2011. Reply #

Hi, I’m using your NSData code to calculate an md5 for a list of files, but I’m having problems comparing the value returned with the value in a string taken from my file list. Should I be able to just use isEqualToString? My code is crashing out when I hit it..

by neil on Jul 27, 2011. Reply #

Thanks, it’s very Nice!!

by fastutle on Oct 12, 2011. Reply #

Thank you, so much your link was very helpful..

by raghul on Jan 30, 2012. Reply #

This code was exactly what I needed, thanks for posting!

by Marc on Mar 29, 2012. Reply #

Hi. What is the licence for this code? I’d like to use it in this project: https://github.com/mindbrix/UIImage-PDF

Best,
Nigel.

by Nigel Barber on Apr 13, 2012. Reply #

You can use the source code in your project, please credit iOSDeveloperTips.com in the comment header.

by John Muchow on Apr 13, 2012. Reply #

I assume this should return the value as the php md5() function? I’m encrypting a string in Xcode and then sending it off to php which calls md5 and compares the 2 strings, but for some reason they don’t match.

by Bill on Aug 1, 2012. Reply #

Leave a Comment