iOS使用MD5 – 字串加密至MD5&擷取檔案MD5

來源:互聯網
上載者:User
iOS 字串加密至MD5
 1 #import <CommonCrypto/CommonDigest.h>
2
3 + (NSString *) md5:(NSString *)str
4 {
5 const char *cStr = [str UTF8String];
6 unsigned char result[16];
7 CC_MD5( cStr, strlen(cStr), result );
8 return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
9 result[0], result[1], result[2], result[3],
10 result[4], result[5], result[6], result[7],
11 result[8], result[9], result[10], result[11],
12 result[12], result[13], result[14], result[15]
13 ];
14 }

  

iPhone處理大檔案檢測MD5的代碼
 1 +(NSString*)fileMD5:(NSString*)path
2 {
3 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
4 if( handle== nil ) return @"ERROR GETTING FILE MD5"; // file didnt exist
5
6 CC_MD5_CTX md5;
7
8 CC_MD5_Init(&md5);
9
10 BOOL done = NO;
11 while(!done)
12 {
13 NSData* fileData = [handle readDataOfLength: CHUNK_SIZE ];
14 CC_MD5_Update(&md5, [fileData bytes], [fileData length]);
15 if( [fileData length] == 0 ) done = YES;
16 }
17 unsigned char digest[CC_MD5_DIGEST_LENGTH];
18 CC_MD5_Final(digest, &md5);
19 NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
20 digest[0], digest[1],
21 digest[2], digest[3],
22 digest[4], digest[5],
23 digest[6], digest[7],
24 digest[8], digest[9],
25 digest[10], digest[11],
26 digest[12], digest[13],
27 digest[14], digest[15]];
28 return s;
29 }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.