我需要帮助在我的 iPhone 应用中获取 MD5 和 SHA-1。 有人能给我一个获取这些的思路吗?
我需要帮助在我的 iPhone 应用中获取 MD5 和 SHA-1。 有人能给我一个获取这些的思路吗?
#include <CommonCrypto/CommonDigest.h>
-(NSString*) sha1:(NSString*)input
{
NSData *data = [input dataUsingEncoding: NSUTF8StringEncoding];
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;
}
- (NSString *) md5:(NSString *) input
{
const char *cStr = [input UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)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;
}
还可以看一下我在这里发布的博客文章 - http://www.makebetterthings.com/blogs/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/
#import <CommonCrypto/CommonDigest.h>
。无需链接 libcommonCrypto.dylib
。 - RaptorNSData *data = [NSData dataWithBytes:cstr length:input.length];
对于非ASCII字符串会出错。我建议使用strlen(cstr)代替input.length。 - Lukas Petr