Objective-C中的MD5算法

如何在Objective-C中计算MD5?



拉丁的传说
浏览 587回答 3
3回答

慕斯王

您可以使用内置的Common Crypto库来执行此操作。记住要导入:#import <CommonCrypto/CommonDigest.h>然后:- (NSString *) md5:(NSString *) input{&nbsp; &nbsp; const char *cStr = [input UTF8String];&nbsp; &nbsp; unsigned char digest[CC_MD5_DIGEST_LENGTH];&nbsp; &nbsp; CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call&nbsp; &nbsp; NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];&nbsp; &nbsp; for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)&nbsp; &nbsp; [output appendFormat:@"%02x", digest[i]];&nbsp; &nbsp; return&nbsp; output;}

函数式编程

如果性能很重要,则可以使用此优化版本。它比使用stringWithFormat或的速度快约5倍NSMutableString。这是NSString的类别。- (NSString *)md5{&nbsp; &nbsp; const char* cStr = [self UTF8String];&nbsp; &nbsp; unsigned char result[CC_MD5_DIGEST_LENGTH];&nbsp; &nbsp; CC_MD5(cStr, strlen(cStr), result);&nbsp; &nbsp; static const char HexEncodeChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };&nbsp; &nbsp; char *resultData = malloc(CC_MD5_DIGEST_LENGTH * 2 + 1);&nbsp; &nbsp; for (uint index = 0; index < CC_MD5_DIGEST_LENGTH; index++) {&nbsp; &nbsp; &nbsp; &nbsp; resultData[index * 2] = HexEncodeChars[(result[index] >> 4)];&nbsp; &nbsp; &nbsp; &nbsp; resultData[index * 2 + 1] = HexEncodeChars[(result[index] % 0x10)];&nbsp; &nbsp; }&nbsp; &nbsp; resultData[CC_MD5_DIGEST_LENGTH * 2] = 0;&nbsp; &nbsp; NSString *resultString = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];&nbsp; &nbsp; free(resultData);&nbsp; &nbsp; return resultString;}
打开App,查看更多内容
随时随地看视频慕课网APP