1.NSString+M5.h(建立一个NSString+M5的分类)
import <Foundation/Foundation.h>
@interface NSString (M5)
//外部调用,用于字符串加密处理
+(NSMutableString * )stringMD5:(NSString *)string;
@end
2.NSString+M5.m
import "NSString+M5.h"
import <CommonCrypto/CommonCrypto.h>
@implementation NSString (M5)
+(NSMutableString * )stringMD5:(NSString *)string{
const char * data=[string UTF8String];
//加密后的数组长度
unsigned char result[CC_MD5_DIGEST_LENGTH];
//加密内容,加密的长度,加密后的长度
CC_MD5(data,(CC_LONG)strlen(data),result);
NSMutableString * mstring = [NSMutableString string];
//
for (int i=0; i<CC_MD5_DIGEST_LENGTH; i++) {
//不足两位前面补0
[mstring appendFormat:@"%02x",result[i]];
}
return string;
}
@end
3.ViewController.m
import "ViewController.h"
//1.导入IOS SDK 自带框架,用于加密(MDS ,SHA)
import <CommonCrypto/CommonCrypto.h>
import "NSString+M5.h"
@interface ViewController ()
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
/*//1.准备需要加密的字符串
NSString * string = @"我爱 我的 同桌";
//2.调用加密使用的函数
//第一个参数:加密的内容
//二:加密的长度
//三:加密后的长度
const char * data = [string UTF8String];
unsigned char result [CC_MD5_DIGEST_LENGTH];
CC_MD5(data, (CC_LONG)strlen(data), result);
//创建一个可变字符串 保存结果
NSMutableString * mString = [NSMutableString string];
//4.遍历结果数组
for (int i = 0 ;i<CC_MD5_DIGEST_LENGTH;i++ ) {
[mString appendFormat:@"%02x",result[i]];}
NSLog(@"mString = %@",mString);pragma mark 对图片进行加密
*/ //获取图片路径
NSString * path=[[NSBundle mainBundle] pathForResource:@"e" ofType:@"jpg"];
//
NSData * data2 = [NSData dataWithContentsOfFile:path];
//加密
// const char * data = [data ];
unsigned char result2 [CC_MD5_DIGEST_LENGTH];
CC_MD5((__bridge const void *)(data2), (CC_LONG)data2.length, result2);
//创建一个可变字符串 保存结果
NSMutableString * mString2 = [NSMutableString string];
//4.遍历结果数组
for (int i = 0 ;i<CC_MD5_DIGEST_LENGTH;i++ ) {
[mString2 appendFormat:@"%02x",result2[i]];}
NSLog(@"mString2 = %@",mString2);
}