MD5 Hash in Objective-C
There is a good way to create StringUtil.m to be reusable for every project...
StringUtil.h
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
@interface StringUitil : NSObject {
}
+ (NSString *)MD5:(NSString *)str;
@end
StringUtil.m
#import "StringUitil.h"
@implementation StringUitil
+ (NSString *)MD5:(NSString *)str {
const char *cStr = [self UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result ); // This is the md5 call
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
example:
NSLog(@"%@",[StringUitl MD5:@"sinzy"]);//output '09db6026d7bdb8dc662e8daae1db19a8'
the second waty to create catalog for NSString and NSData
MyAddition.h
@interface NSString (MyAddition)
- (NSString *)md5;
@end
@interface NSData (MyAddition)
- (NSString *)md5;
@end
MyAddition.m
#import "MyAddition.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (MyAddition)
- (NSString *)md5 {
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result ); ;//This is the md5 call
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
@implementation NSData (MyAddition)
- (NSString*)md5
{
unsigned char result[16];
CC_MD5( self.bytes, self.length, result ); // This is the md5 call
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
example:
NSLog(@"%@", [@"sinzy" md5]);//09db6026d7bdb8dc662e8daae1db19a8
MD5 generator online by php language:
http://www.adamek.biz/md5-generator.php
语法真够恶心的……
objC 的语法的确这样,但最近在编程语言排行榜上升挺快的~估计都是iphone程式的原因...