Created
March 20, 2011 16:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Cocoa/Cocoa.h> | |
#import <CommonCrypto/CommonDigest.h> | |
@interface NSString (md5) | |
-(NSString *) md5HexDigest; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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
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 thanlowercaseString
at the end?