How to get md5 and SHA1 in objective c (iOS sdk)
Calculating the md5 and sha1 hash in iOS sdk is pretty simple -
Step 1 – The very first thing you need to do is import CommonCrypto’s CommonDigest.h
1 |
#import <CommonCrypto/CommonDigest.h> |
Step 2 – Here is the real code for calculating SHA1 and MD5 hash -
SHA1 -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
-( NSString *) sha1:( NSString *)input { const
char *cstr = [input cStringUsingEncoding: NSUTF8StringEncoding ]; NSData
*data = [ NSData
dataWithBytes:cstr length:input.length]; 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; } |
MD5 -
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
- ( NSString
*) md5:( NSString
*) input { const
char *cStr = [input UTF8String]; unsigned char
digest[16]; CC_MD5( cStr, 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; } |
Hope it will help someone!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。