Skip to content

Instantly share code, notes, and snippets.

@emaxerrno
Forked from gnrfan/NSString+MD5HexDigest.h
Created September 12, 2011 20:07
Show Gist options
  • Save emaxerrno/1212241 to your computer and use it in GitHub Desktop.
Save emaxerrno/1212241 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment