2015-01-24
MD5 这种加密算法应该属于每天都要被用到的东西,然而,iOS 只提供了这个方法给我们使用。
extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)
#import "NSString+Md5.h" #import <CommonCrypto/CommonCrypto.h> @implementation NSString (Md5) - (NSString *)md5String { const char *str = [(NSString *)self UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH] = {0}; CC_MD5(str, (CC_LONG)strlen(str), result); NSMutableString *ret = [NSMutableString string]; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { [ret appendFormat:@"%02x", result[i]]; } return ret; } @end
#import "NSData+Md5.h" #import <CommonCrypto/CommonCrypto.h> @implementation NSData (Md5) - (NSString *)md5String { const char *str = [self bytes]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)self.length, result); NSMutableString *hash = [NSMutableString string]; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { [hash appendFormat:@"%02X", result[i]]; } return [hash lowercaseString]; } @end
NSString *test = @"我"; NSLog(@"%lu",(unsigned long)test.length); const char *cTest = [test UTF8String]; NSLog(@"%lu",strlen(cTest));
NSLog(@"%c",[test characterAtIndex:0]); NSLog(@"%@",[test substringWithRange:NSMakeRange(0, 1)]);
NSString *test = @"aaa\0bbb"; NSLog(@"%lu",(unsigned long)test.length); const char *cTest = [test UTF8String]; NSLog(@"%lu",strlen(cTest));
NSString *test = @"aaa"; NSLog(@"%@",[test md5StringStr]); NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",[data md5String]);
NSString *test = @"aaa\0bbb"; NSLog(@"%@",[test md5StringStr]); NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",[data md5String]);
//NSData 的 MD5 方法不变 #import "NSData+Md5.h" #import <CommonCrypto/CommonCrypto.h> @implementation NSData (Md5) - (NSString *)md5String { const char *str = [self bytes]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)self.length, result); NSMutableString *hash = [NSMutableString string]; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { [hash appendFormat:@"%02X", result[i]]; } return [hash lowercaseString]; } @end //NSString 的 MD5 转化为 NSData,通过 NSData 的 MD5 计算返回结果 #import "NSString+Md5.h" #import "NSData+Md5.h" @implementation NSString (Md5) - (NSString *)md5String { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; return [data md5String]; } @end