Skip to content

Instantly share code, notes, and snippets.

@hulefei
Last active April 6, 2016 02:33
Show Gist options
  • Save hulefei/7fe62695014889caee42f61c456b1fcf to your computer and use it in GitHub Desktop.
Save hulefei/7fe62695014889caee42f61c456b1fcf to your computer and use it in GitHub Desktop.
IOS Objective-C 版本 MD5加密
import <CommonCrypto/CommonDigest.h> // md5需要引用这个文件
// md5 32位 加密
+ (NSString *) MD5:(NSString *) string {
const charchar *cStr = [string UTF8String];
unsigned char result[16];
CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
//%02x 格式控制: 以十六进制输出,2为指定的输出字段的宽度.如果位数小于2,则左端补0
NSString *output = [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]
];
NSLog(@"MD5 %@", output);
return output;
}
// 优化下,变成这样
+ (NSString *) MD5:(NSString *) string {
const charchar *cStr = [string UTF8String];
unsigned char digest[16];
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]];
NSLog(@"MD5 %@", output);
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment