Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to encrypt an NSDictionary when writing to file

Tags:

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

like image 755
Rich Brooks Avatar asked May 05 '11 10:05

Rich Brooks


People also ask

How do I encrypt a file in shell script?

You can save a key to a file by running ./encrypt.sh -g > encryption. key . To encrypt a file use the -e option and specify the {input-file} (file to encrypt) and {output-file} (encrypted file). You can use a -k Key, -p Password, or leave the parameter blank in order to be prompted for a password.


1 Answers

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.

like image 92
DarkDust Avatar answered Sep 28 '22 09:09

DarkDust