尝试在写入文件时加密NSDictionary [英] Trying to encrypt an NSDictionary when writing to file
问题描述
我目前正在保存文件:
NSFileManager * fileManager = [NSFileManager defaultManager];
如果(!fileManager)
{
NSLog(@无法获取文件管理器保存);
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];
任何人都可以告诉我一个很好的加密方式,加密这个吗?
Cheers,
Rich
使用 NSKeyedArchiver
从您的字典创建一个 NSData
对象( NSKeyedArchiver archivedDataWithRootObject:)。然后使用AES加密NSData ,并将其写入您的文件。 / p>
阅读反过来:首先,读取NSData,通过上述链接的方法对其进行解密,然后将解密后的NSData传递给NSKeyedUnarchiver( NSKeyedUnarchiver unarchiveObjectWithData:),并且您的字典返回。
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
Use a NSKeyedArchiver
to create an NSData
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.
这篇关于尝试在写入文件时加密NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!