21

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

Rich Brooks
  • 521
  • 1
  • 6
  • 17

1 Answers1

23

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.

Community
  • 1
  • 1
DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • 1
    @DarkDust [NSKeyedUnarchiver unarchiveObjectWithData:someArchivedDictionary] returning NSData instance instead of NSMutableDictionary. I am following the steps you suggested: Archive -> Encrypt with AES -> Store to file -> Read from file -> Decrypt with AES -> Unarchive. Any idea what might be the problem? If you request i can post it as new question. – Gökhan Barış Aker Sep 16 '12 at 19:40
  • Why not use the file protection APIs instead of trying to implement encryption yourself? – Steve Moser Sep 21 '15 at 19:48
  • 1
    @SteveMoser The data protection API is good when the phone is locked. You may still want to have your data encrypted when the screen is unlocked or in the event that the data protection on the device is compromised. – NSDestr0yer Apr 18 '16 at 19:00