iOS里加密字符串、图片、视频方法
GTMDefines.h GTMBase64.h GTMBase64.m
2、编解码函数(可以编解码字符串、图片、视频:filePath换成相应的即可): 从模拟器和真机的Documents路径下读取文件,编码后写入文件;读出来解码
// 加密函数 -(void)func_encodeFile { //NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/test.png"]; NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/iphone4.mov"];
//文件路径转换为NSData NSData *imageDataOrigin = [NSData dataWithContentsOfFile:filePath];
// 对前1000位进行异或处理 unsigned char * cByte = (unsigned char*)[imageDataOrigin bytes]; for (int index = 0; (index < [imageDataOrigin length]) && (index < 1000); index++, cByte++) { *cByte = (*cByte) ^ arrayForEncode[index]; }
//对NSData进行base64编码 NSData *imageDataEncode = [GTMBase64 encodeData:imageDataOrigin];
[imageDataEncode writeToFile:filePath atomically:YES]; }
// 解密函数 -(void)func_decodeFile { //NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/test.png"]; NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/iphone4.mov"];
// 读取被加密文件对应的数据 NSData *dataEncoded = [NSData dataWithContentsOfFile:filePath];
// 对NSData进行base64解码 NSData *dataDecode = [GTMBase64 decodeData:dataEncoded];
// 对前1000位进行异或处理 unsigned char * cByte = (unsigned char*)[dataDecode bytes]; for (int index = 0; (index < [dataDecode length]) && (index < 1000); index++, cByte++) { *cByte = (*cByte) ^ arrayForEncode[index]; }
[dataDecode writeToFile:filePath atomically:YES]; }
下面是根据上面2中的代码实现成功而来:
#define Key_Count (10)//加密字符串长度,上文2中设置1000,此处便于理解测试设置为10
-(BOOL)func_encodeFile:(NSString *)filePath withNewName:(NSString*)newFilePath
测试代码段:
NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/test/1.jpg"]; |
|
来自: 叹落花 > 《字符,图片,视频加密》