//
// main.m
// MD5
//
// Created by dc008 on 16/1/5.
// Copyright © 2016年 lin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "NSString+Extend.h"
int main() {
[@"习近平" sayHi];
NSLog(@"%@",[@"崔晓宇" md5]);
//IOS7 以后提供了 base64 的转码方式
//编码
NSString *password = @"cxy";
NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *result = [passwordData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSLog(@"%@",result);
//解码
NSData *decodeData = [[NSData alloc]initWithBase64EncodedString:result options:0];
NSString *decodeStr = [[NSString alloc]initWithData:decodeData encoding:NSASCIIStringEncoding];
NSLog(@"%@",decodeStr);
return 0;
}
//
// NSString+Extend.h
// MD5
//
// Created by dc008 on 16/1/5.
// Copyright © 2016年 lin. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString(Extend)
- (void)sayHi;
- (NSString *)md5;
@end
//
// NSString+Extend.m
// MD5
//
// Created by dc008 on 16/1/5.
// Copyright © 2016年 lin. All rights reserved.
//
#import "NSString+Extend.h"
#import <CommonCrypto/CommonCrypto.h>
@implementation NSString(Extend)
- (void)sayHi{
NSLog(@"%@ 说你好",self);
}
- (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值
//%02X
NSMutableString *str = [NSMutableString stringWithCapacity:10];
for (int i = 0; i < 16; i++) {
[str appendString:[NSString stringWithFormat:@"%02X",result[i]]];
}
return str;
}
@end