This is the category I use:
NSString+MD5.h
@interface NSString (MD5)
- (NSString *)MD5String;
@end
NSString+MD5.m
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (MD5)
- (NSString *)MD5String {
const char *cStr = [self UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
return [NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
@end
Usage
NSString *myString = @"test";
NSString *md5 = [myString MD5String]; // returns NSString of the MD5 of test
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…