3 回答

TA貢獻1864條經驗 獲得超2個贊
您可以使用內置的Common Crypto庫來執行此操作。記住要導入:
#import <CommonCrypto/CommonDigest.h>
然后:
- (NSString *) md5:(NSString *) input
{
const char *cStr = [input UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}

TA貢獻1807條經驗 獲得超9個贊
如果性能很重要,則可以使用此優化版本。它比使用stringWithFormat或的速度快約5倍NSMutableString。
這是NSString的類別。
- (NSString *)md5
{
const char* cStr = [self UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);
static const char HexEncodeChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char *resultData = malloc(CC_MD5_DIGEST_LENGTH * 2 + 1);
for (uint index = 0; index < CC_MD5_DIGEST_LENGTH; index++) {
resultData[index * 2] = HexEncodeChars[(result[index] >> 4)];
resultData[index * 2 + 1] = HexEncodeChars[(result[index] % 0x10)];
}
resultData[CC_MD5_DIGEST_LENGTH * 2] = 0;
NSString *resultString = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];
free(resultData);
return resultString;
}
- 3 回答
- 0 關注
- 708 瀏覽
添加回答
舉報