获取MD5和SHA-1

时间:2011-05-15 05:48:33

标签: ios objective-c md5 sha

我正在寻找帮助在我的iPhone应用程序中获取MD5和SHA-1。 谁能告诉我如何获得这些?

1 个答案:

答案 0 :(得分:16)

#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/