Skip to content

Instantly share code, notes, and snippets.

@gnrfan
Created March 20, 2011 16:45
Show Gist options
  • Save gnrfan/878443 to your computer and use it in GitHub Desktop.
Save gnrfan/878443 to your computer and use it in GitHub Desktop.
Extending the NSString class with a MD5 hex digest method using a category
#import <Foundation/Foundation.h>
#import "NSString+MD5HexDigest.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str = [NSString stringWithString:@"test"];
NSString *md5;
NSLog(@"String: %@", str);
md5 = [str md5HexDigest];
NSLog(@"MD5 Hash: %@",md5); /* Should be "098f6bcd4621d373cade4e832627b4f6" */
[pool drain];
return 0;
}
#import <Cocoa/Cocoa.h>
#import <CommonCrypto/CommonDigest.h>
@interface NSString (md5)
-(NSString *) md5HexDigest;
@end
#import "NSString+MD5HexDigest.h"
@implementation NSString (md5)
-(NSString *) md5HexDigest
{
const char *original_str = [self UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(original_str, strlen(original_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
[hash appendFormat:@"%02X", result[i]];
return [hash lowercaseString];
}
@end
@haikusw
Copy link

haikusw commented Sep 1, 2011

Might replace:

NSMutableString *hash = [NSMutableString string];

with:

NSMutableString *hash = [NSMutableString stringWithCapacity: 32];

since it might be more efficient since that hints to the allocator to make space for 32 chars. The default might be large enough so this doesn't matter, but if it's too much larger then this might help the other way and save memory.

Also, why not use %02x to make it lower case during string generation rather than lowercaseString at the end?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment