- 使用AES加密在平时开发中对NSString加密比较常见,因项目需求,需要多资源文件(如:图片)和plist(Info.plist)文件加密。
- 话不多说,直接上代码
有使用到RNCryptor-objc的第三方库
pod 'RNCryptor-objc'
创建工具类
//
// LCArchiveManager.h
// LCAESFileEncryption
//
// Created by yxl on 2022/4/1.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface LCArchiveManager : NSObject
/// 图片加密
+(void)imageEncryptionImageName:(NSString *)imageName Type:(NSString *)type;
/// 图片解密获取
+(UIImage *)imageDecryptionImageFileName:(NSString *)imageFileName;
/// Plist文件加密
+(void)plistEncryptionPlistName:(NSString *)plistName Type:(NSString *)type;
/// Plist解密获取
+(NSDictionary *)plistDecryptionPlistFileName:(NSString *)plistFileName;
/// 清除本地的序列化的文件
+(void)clearArchiverData;
@end
NS_ASSUME_NONNULL_END
//
// LCArchiveManager.m
// LCAESFileEncryption
//
// Created by yxl on 2022/4/1.
//
#import "LCArchiveManager.h"
#import "RNEncryptor.h"
#import "RNDecryptor.h"
#define aPassword @"LCArchiveManagerPassword"
@implementation LCArchiveManager
#pragma mark --Image加解密
/// 图片加密
+(void)imageEncryptionImageName:(NSString *)imageName Type:(NSString *)type
{
NSString *filePath = [[NSBundle mainBundle]pathForResource:imageName ofType:type];
__block NSData *data = [NSData dataWithContentsOfFile:filePath];
__block NSError *error;
// 本地存储加密图片路径
NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",imageName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断是否已存在加密文件,若存在直接执行解密过程。
if ([fileManager fileExistsAtPath:fileEncryPath]) {
return;
}
//异步去加密,防止占用太多内存
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//加密
NSData *encryptedData = [RNEncryptor encryptData:data withSettings:kRNCryptorAES256Settings password:aPassword error:&error ];
if (!error) {
NSLog(@"^_^ 图片加密成功 ……——(^_^)\n");
}
//在主线程上写入文件
dispatch_sync(dispatch_get_main_queue(), ^{
BOOL yes = [encryptedData writeToFile:fileEncryPath atomically:NO];
if (yes) {
NSLog(@"加密图片文件写入成功");
}else{
NSLog(@"加密图片文件写入失败");
}
NSLog(@"图片写入PDF路径:%@",fileEncryPath);
});
});
}
/// 图片解密获取
+(UIImage *)imageDecryptionImageFileName:(NSString *)imageFileName{
NSString *fileDecryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",imageFileName]];
NSData *encryptedData = [NSData dataWithContentsOfFile:fileDecryPath];
NSError *error;
NSData *decryptedData = [RNDecryptor decryptData:encryptedData
withPassword:aPassword
error:&error];
if (!error) {
NSLog(@"^_^ 图片解密成功 ……——(^_^)\n");
return [UIImage imageWithData:decryptedData];
}
return nil;
}
#pragma mark - Plist文件加解密
/// Plist文件加密
+(void)plistEncryptionPlistName:(NSString *)plistName Type:(NSString *)type{
__block NSData *encryptedData;
__block NSError *error;
// 本地存储加密图片路径
NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断是否已存在加密文件,若存在直接执行解密过程。
if ([fileManager fileExistsAtPath:fileEncryPath]) {
return;
}
NSURL *URL=[[NSBundle mainBundle] URLForResource:plistName withExtension:type];
//plist 文件为字典类型
NSDictionary *dic=[NSDictionary dictionaryWithContentsOfURL:URL];
NSError *parseError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
//异步去加密,防止占用太多内存
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//加密
encryptedData = [RNEncryptor encryptData:jsonData withSettings:kRNCryptorAES256Settings password:aPassword error:&error ];
if (!error) {
NSLog(@"^_^ plist文件加密成功 ……——(^_^)\n");
}
//在主线程上写入文件
dispatch_sync(dispatch_get_main_queue(), ^{
BOOL yes = [encryptedData writeToFile:fileEncryPath atomically:NO];
if (yes) {
NSLog(@"加密plist文件写入成功");
}else{
NSLog(@"加密plist文件写入失败");
}
NSLog(@"写入plist路径:%@",fileEncryPath);
});
});
}
/// Plist解密获取
+(NSDictionary *)plistDecryptionPlistFileName:(NSString *)plistFileName{
NSString *fileDecryPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/%@",plistFileName]];
NSData *encryptedData = [NSData dataWithContentsOfFile:fileDecryPath];
// 解密
NSError *error;
NSData *decryptedData = [RNDecryptor decryptData:encryptedData
withPassword:aPassword
error:&error];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:decryptedData options:NSJSONReadingMutableContainers error:&error];
if (error) {
//解析出错
NSLog(@"error===%@",error);
}
return dic;
}
#pragma mark - 清除
+(void)clearArchiverData
{
NSError *error;
NSString *fileEncryPath = [NSHomeDirectory()stringByAppendingPathComponent:@"/Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager removeItemAtPath:fileEncryPath error:&error]){
NSLog(@"清除本地序列化的文件成功....:%@",error);
} else {
NSLog(@"清除本地序列化的文件失败....:%@",error);
}
}
@end
使用
//
// ViewController.m
// LCAESFileEncryption
//
// Created by yxl on 2022/4/1.
//
#import "ViewController.h"
#import "LCArchiveManager.h"
@interface ViewController ()
@property(strong,nonatomic)UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createUI];
[self imageEncryption];
[self plistEncryption];
}
#pragma mark - 加密
// 加密image
- (void)imageEncryption{
[LCArchiveManager imageEncryptionImageName:@"testImage" Type:@"jpg"];
}
// 加密plist文件
- (void)plistEncryption{
[LCArchiveManager plistEncryptionPlistName:@"Info" Type:@"plist"];
}
#pragma mark - 解密
// 解密图片
- (void)imageClicked{
self.imageView.image = [LCArchiveManager imageDecryptionImageFileName:@"testImage"];
}
// 解密plist文件
- (void)plistClicked{
NSDictionary *dic = [LCArchiveManager plistDecryptionPlistFileName:@"Info"];
NSLog(@"dic=====%@",dic);
}
#pragma mark - 清除加密文件
- (void)clearClicked{
[LCArchiveManager clearArchiverData];
}
-(void)createUI
{
CGFloat iPhoneHeight = self.view.bounds.size.height;
CGFloat iPhoneWidth = self.view.bounds.size.width;
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(50.f, 100.f, iPhoneWidth-100.f, 50.f)];
[button addTarget:self action:@selector(plistClicked) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"查看PLIST" forState:UIControlStateNormal];
button.layer.cornerRadius = 5.f;
button.clipsToBounds = YES;
button.layer.borderWidth = 1.f;
button.layer.borderColor = [UIColor blackColor].CGColor;
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:button];
UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(50.f, 200.f, iPhoneWidth-100.f, 50.f)];
[button1 addTarget:self action:@selector(imageClicked) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:@"查看图片" forState:UIControlStateNormal];
button1.layer.cornerRadius = 5.f;
button1.clipsToBounds = YES;
button1.layer.borderWidth = 1.f;
button1.layer.borderColor = [UIColor blackColor].CGColor;
[button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:button1];
UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(50.f, 300.f, iPhoneWidth-100.f, 50.f)];
[button2 addTarget:self action:@selector(clearClicked) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:@"清除加密文件" forState:UIControlStateNormal];
button2.layer.cornerRadius = 5.f;
button2.clipsToBounds = YES;
button2.layer.borderWidth = 1.f;
button2.layer.borderColor = [UIColor blackColor].CGColor;
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:button2];
self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, iPhoneHeight/2, iPhoneWidth-20, 300)];
self.imageView.layer.borderColor = [UIColor blackColor].CGColor;
self.imageView.layer.borderWidth = 1.f;
self.imageView.clipsToBounds = YES;
self.imageView.layer.cornerRadius = 5.f;
[self.view addSubview:self.imageView];
}
@end
网友评论