Create MD5 Hash from NSString, NSData or a File

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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章