感谢作者:http://www./2011/08/13/用CommonCrypto计算MD5和SHA 编程时经常需要和MD5、SHA等hash算法打交道,搜了一下后我发现iOS SDK中自带了CommonCrypto,于是就无需自己实现或用第三方库了。 #include <CommonCrypto/CommonDigest.h> static inline char hexChar(unsigned char c) { return c < 10 ? '0' + c : 'a' + c - 10; } static inline void hexString(unsigned char *from, char *to, NSUInteger length) { for (NSUInteger i = 0; i < length; ++i) { unsigned char c = from[i]; unsigned char cHigh = c >> 4; unsigned char cLow = c & 0xf; to[2 * i] = hexChar(cHigh); to[2 * i + 1] = hexChar(cLow); } to[2 * length] = '\0'; } NSString * md5(const char *string) { static const NSUInteger LENGTH = 16; unsigned char result[LENGTH]; CC_MD5(string, (CC_LONG)strlen(string), result); char hexResult[2 * LENGTH + 1]; hexString(result, hexResult, LENGTH); return [NSString stringWithUTF8String:hexResult]; } NSLog(@"%@", md5("test")); 这里首先是调用CC_MD5()来计算,不过它的计算结果是字符数组,而一般我们是使用16进制格式的字符串。 NSString * sha1(const char *string) { static const NSUInteger LENGTH = 20; unsigned char result[LENGTH]; CC_SHA1(string, (CC_LONG)strlen(string), result); char hexResult[2 * LENGTH + 1]; hexString(result, hexResult, LENGTH); return [NSString stringWithUTF8String:hexResult]; } NSLog(@"%@", sha1("test")); 逻辑几乎是一样的,所以就不再解释了。 |
|