写入文件时尝试加密 NSDictionary
我目前正在将 NSDictionary 保存到 iOS 设备上的文件中。然而,NSDictionary 文件是可读的 XML。我不希望人们能够进入并阅读内容,因此我需要能够在写入时加密文件并在再次加载时解密。
我目前正在像这样保存文件:
NSFileManager* fileManager = [NSFileManager defaultManager];
if (!fileManager)
{
NSLog(@"Failed to get file manager to save.");
return;
}
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"save.dic"];
[m_dictionary writeToFile:filePath atomically:YES];
我正在像这样加载字典:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"save.dic"];
m_dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
谁能告诉我一种加密\解密的好方法?
干杯, 富有的
I'm currently saving an NSDictionary to file on the iOS device. However, NSDictionary files are readable XML. I don't want people to be able to get in and read the contents so I need to be able to encrypt the file on writing and decrypt when loading it back again.
I'm currently saving the file like this:
NSFileManager* fileManager = [NSFileManager defaultManager];
if (!fileManager)
{
NSLog(@"Failed to get file manager to save.");
return;
}
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"save.dic"];
[m_dictionary writeToFile:filePath atomically:YES];
And I'm loading the dictionary like this:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:@"save.dic"];
m_dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
Can anyone tell me a nice way of encrypting\decrypting this?
Cheers,
Rich
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
NSKeyedArchiver
从字典中创建NSData
对象(NSKeyedArchiver archivedDataWithRootObject:)。然后使用 AES 加密 NSData 并将其写入您的文件。读取则相反:首先读取 NSData,通过上述链接中的方法对其进行解密,然后将解密后的 NSData 传递给 NSKeyedUnarchiver (NSKeyedUnarchiver unarchiveObjectWithData:) 然后你就可以拿回你的字典了。
Use a
NSKeyedArchiver
to create anNSData
object from your dictionary (NSKeyedArchiver archivedDataWithRootObject:). Then encrypt the NSData with AES and write that to your file.Reading takes the reverse: first, read the NSData, decrypt it via the method from the mentioned link, then pass the decrypted NSData to NSKeyedUnarchiver (NSKeyedUnarchiver unarchiveObjectWithData:) and you get your dictionary back.