一、無中文字符串加密
1.1 導(dǎo)入頭文件
#import<CommonCrypto/CommonDigest.h>
1.2 代碼
//sha1加密方式
- (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, (unsigned int)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;
}
二、含中文字符串加密
2.1 導(dǎo)入頭文件
#import<CommonCrypto/CommonDigest.h>
2.2 代碼
//sha1加密方式
- (NSString *) sha1:(NSString *)input
{
//這兩句容易造成 、中文字符串轉(zhuǎn)data時(shí)會(huì)造成數(shù)據(jù)丟失
//const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
//NSData *data = [NSData dataWithBytes:cstr length:input.length];
//instead of
NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (unsigned int)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;
}
第二種方法的加密方式適用于純字符串以及帶有中文的字符串,
推薦使用,推薦使用陆蟆,推薦使用!M镌觥叠殷!
參考文獻(xiàn):
http://www.cnblogs.com/On1Key/p/5458782.html
http://www.cocoachina.com/bbs/read.php?tid=263440&page=e