iOS裡加密字串、圖片、視頻方法
1、使用GTMBase64編碼解碼字串
GTMDefines.hGTMBase64.hGTMBase64.m
你可以在這裡找到這三個檔案(GTMDefines.h在第二頁,點擊右上方的next按鈕即可跳轉到第二頁)http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/?r=87
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 < 10); index++, cByte++)
{
*cByte = (*cByte) ^ arrayForEncode[index];
}
[dataDecode writeToFile:filePath atomically:YES];
}