2011-05-15 67 views
10

我正在尋找一些在我的iPhone應用程序中獲取MD5和SHA-1的幫助。 任何人都可以給我一個關於如何得到這些的想法嗎?獲取MD5和SHA-1

+0

@ user754229:如果你用Google搜索http://www.google.com/search?rlz=1C1SNNT_enUS377US377&sourceid=chrome&ie=UTF-8&q = + +目標+ c +(iPhone)+ + + + + + + + + sha1 +索拉布的答案應該是結果中的第四個環節。 – 2011-05-15 05:58:34

+1

@Paul:SO正在努力整合所有信息,以便Google將人員帶到這裏。 http://meta.stackexchange.com/questions/87652/discourage-google-for-it-answers – 2011-05-15 06:45:27

回答

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/

+0

非常感謝! – user754229 2011-05-15 05:53:07

+1

不要忘記在實現代碼的頂部添加'#import '。無需鏈接到'libcommonCrypto.dylib' – Raptor 2012-02-10 07:22:25

+0

爲什麼你用CC_SHA1_DIGEST_LENGTH * 2初始化mutableString,而不是僅僅執行[NSMutableString string]? – Oliver 2012-07-09 03:15:07