UI进阶之网络进阶MD5及对本地数据的加密

方法一:

引入头文件
#import "ViewController.h"

#import <CommonCrypto/CommonCrypto.h>

- (void)viewDidLoad {
    [super viewDidLoad];

    //1:准备好一个字符串
    NSString *string = @"共郭德亚梁地方郭德纲的郭德纲的风格的风格第三方士大夫士大夫是 阿范德萨范德萨发放的爽肤水水电费水电费水电费对方水电费空间和空间和空间和空间和空间和空间还看见看见了包括了基";
   
    //2:MD5 加密是基于C语言的, 所以要把这个字符串转化成c的字符串
    const char *footData = [string UTF8String];

    //3: 创建一个字符串数组, 接收MD5的值
    unsigned char result[CC_MD5_DIGEST_LENGTH];

    //4: 计算MD5的值
    //第一个参数: 表示要加密的字符串
    //第二个参数: 获取要加密字符串的长度
    //第三个参数: 接收结果的数组
    CC_MD5(footData, (CC_LONG)strlen(footData), result);

    //5: 保存结果的字符串
    NSMutableString *resultString = [NSMutableString string];

    //6:从result数组中获取最终结果
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        
        [resultString appendFormat:@"%02X", result[i]];
        
    }
    NSLog(@"result == %@", resultString);
    

}

 

方法二:

创建MD5的类目,在ViewController中调用即可

 

#import "NSString+MD5.h"

#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (MD5)


- (NSString *)getMD5String
{
    const char *data = [self UTF8String];
    
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(data, (CC_LONG)strlen(data), result);
    
    NSMutableString *string = [NSMutableString string];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        
        [string appendFormat:@"%02X", result[i]];
        
    }
    NSLog(@"string == %@", string);
    

    return string;
}

 

 

 

对本地数据的加密

 

- (void)viewDidLoad {
    [super viewDidLoad];
 NSString *docunment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    NSArray *array = @[@"1", @"2"];
    
    
    NSString *path = [docunment stringByAppendingPathComponent:@"array.plist"];
    
    [array writeToFile:path atomically:YES];
    
    NSLog(@"array == %@", docunment);
    
    // NSLog(@"document = %@", docunment);
    
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    NSLog(@"data == %@", data);
    
    //1: 创建一个MD5的对象
    
    CC_MD5_CTX md5;
    
    //2.初始化MD5对象
    
    CC_MD5_Init(&md5);
    
    //3.准备MD5的加密
    
    CC_MD5_Update(&md5, data.bytes, (CC_LONG)data.length);
    
    //4.准备一个字符串数组, 存储MD5加密之后的数据
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    //5.结束MD5的加密
    
    CC_MD5_Final(result, &md5);
    
    
    NSMutableString *resultString = [NSMutableString string];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        
        [resultString appendFormat:@"%02X", result[i]];
    }
    NSLog(@"reslit == %@", resultString);
    
}

 

posted @ 2016-04-07 20:30  胡一波  阅读(123)  评论(0编辑  收藏  举报