NSString+Encryption.h
// // NSString+Encryption.h // haochang // // Created by Administrator on 14-4-15. // Copyright (c) 2014年 Administrator. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (Encryption) + (NSString *)md5:(NSString *)str; + (NSString*) sha1:(NSString *)str; @end
NSString+Encryption.m
// // NSString+Encryption.m // haochang // // Created by Administrator on 14-4-15. // Copyright (c) 2014年 Administrator. All rights reserved. // #import "NSString+Encryption.h" #import <CommonCrypto/CommonDigest.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/sockio.h> #include <net/if.h> #include <errno.h> #include <net/if_dl.h> #include <ifaddrs.h> #include <arpa/inet.h> #define min(a,b) ((a) < (b) ? (a) : (b)) #define max(a,b) ((a) > (b) ? (a) : (b)) @implementation NSString (Encryption) + (NSString *)md5:(NSString *)str{ const char *cStr = [str UTF8String]; unsigned char result[16]; CC_MD5(cStr, strlen(cStr), result); // This is the md5 call 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] ]; } + (NSString*) sha1:(NSString *)str { const char *cstr = [str cStringUsingEncoding:NSUTF8StringEncoding]; NSData *data = [NSData dataWithBytes:cstr length:str.length]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, data.length, digest); NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } @end