main.m文件數組
// main.mapp
// 加密 MD5函數
#import <Foundation/Foundation.h>編碼
#import "NSString+Extend.h"加密
int main(int argc, const char * argv[]) {spa
NSLog(@"%@",[@"123456" md5]);3d
//IOS 之後提供了 base64 的轉碼方式code
NSString * password=@"123456";orm
NSData *passwordData=[password dataUsingEncoding:NSUTF8StringEncoding];md5
NSString * result=[passwordData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSLog(@" base64編碼: %@",result);
//解碼
NSData * decodeData=[[NSData alloc]initWithBase64EncodedString:result options:0];
NSString * decodestr=[[NSString alloc]initWithData:decodeData encoding:NSASCIIStringEncoding];
NSLog(@" base64解碼: %@",decodestr);
return 0;
}
.h文件 加密解密(NSString擴展類)
——————————————————————————————————————————————
#import <Foundation/Foundation.h>
@interface NSString(Extend)
-(NSString * )md5;
@end
----————————————————————————————————————————————
.m文件
#import "NSString+Extend.h"
//引入頭文件
#import <CommonCrypto/CommonDigest.h>
@implementation NSString(Extend)
-(NSString * )md5{
//轉換成C語言的字符串
const char * cstr=[self UTF8String];
//MD5加密的結果是128位,須要開闢16字節的空間
unsigned char result[16];
//調用函數
CC_MD5(cstr, (unsigned int)strlen(cstr), result);
//經過上面這個方法獲取的MD5是一個16個字符串的數組----> 32位的MD5
NSMutableString * mustr=[NSMutableString stringWithCapacity:10];
for (int i=0; i<16; i++) {
[mustr appendString:[NSString stringWithFormat:@"%02X",result[i]]];
}
return mustr;
}
@end