需要导入的头文件#import <CommonCrypto/CommonCrypto.h>
MD5加密(NSData -> NSData)
+ (NSData *)toMD5:(NSData *)data {
@try {
unsigned char result[16];
CC_MD5([data bytes], (CC_LONG)[data length], result);
return [NSData dataWithBytes:result length:16];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
return nil;
}
}
MD5加密字符串,生成字符串(NSString -> NSString)
+ (NSString *)toMD5String:(NSString *)source {
@try {
if (!source || ![source isKindOfClass:[NSString class]]) {
return nil;
}
const char *cStr = [source UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG) strlen(cStr), result);
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]];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
return nil;
}
}
MD5加密字符串,生成Data (NSString -> NSData)
+ (NSData *)toMD5Data:(NSString *)source {
@try {
if (!source || ![source isKindOfClass:[NSString class]]) {
return nil;
}
const char *cStr = [source UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG) strlen(cStr), result);
return [NSData dataWithBytes:result length:16];
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
return nil;
}
}
网友评论