标签:
NSString+Password.h
1 // 2 // NSString+Password.h 3 // 03.数据加密 4 // 5 // Created by wyh on 15-1-10. 6 // Copyright (c) 2015年 itcast. All rights reserved. 7 // 8 9 10 #import <Foundation/Foundation.h> 11 12 @interface NSString (Password) 13 14 /** 15 * 32位MD5加密 16 * 17 * @return 32位MD5加密结果 18 */ 19 - (NSString *)MD5; 20 21 /** 22 * SHA1加密 23 * 24 * @return SHA1加密结果 25 */ 26 - (NSString *)SHA1; 27 28 @end
1 // 2 // NSString+Password.m 3 // 数据加密 4 // 5 // Created by wyh on 15-1-10. 6 // Copyright (c) 2015年 itcast. All rights reserved. 7 // 8 9 #import "NSString+Password.h" 10 #import <CommonCrypto/CommonDigest.h> 11 12 @implementation NSString (Password) 13 14 #pragma mark 使用MD5加密字符串 15 - (NSString *)MD5 16 { 17 const char *cStr = [self UTF8String]; 18 unsigned char digest[CC_MD5_DIGEST_LENGTH]; 19 20 CC_MD5(cStr, strlen(cStr), digest); 21 22 NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; 23 24 for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { 25 [result appendFormat:@"%02x", digest[i]]; 26 } 27 28 return result; 29 } 30 31 #pragma mark 使用SHA1加密字符串 32 - (NSString *)SHA1 33 { 34 const char *cStr = [self UTF8String]; 35 NSData *data = [NSData dataWithBytes:cStr length:self.length]; 36 uint8_t digest[CC_SHA1_DIGEST_LENGTH]; 37 38 CC_SHA1(data.bytes, data.length, digest); 39 40 NSMutableString *result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; 41 42 for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { 43 [result appendFormat:@"%02x", digest[i]]; 44 } 45 46 return result; 47 } 48 49 @end
使用步骤:
在使用的类中加入类目:#import "NSString+Password.h"
用要加密的字符串调方法MD5或SHA1,返回加密后的字符串:加密结果=[self.userPwd.text MD5];
结束
标签:
原文地址:http://www.cnblogs.com/wangyinghui/p/4353724.html