How to encrypt/decrypt the files such as (.pdf,.txt) while saving and reading from the NSDocumentDirectory

408 views Asked by At

I'm currently saving a PDF file on the iOS device. 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.I am getting a Base64 String which has pdf contents plus password from the service, what I am doing is I am converting to NSData and saving to NSDocumentDirectory and I use that file path to open in UIDocumentInteractionController While opening pdf I get a password prompt in UIDocumentInteractionController and is working as expected:

 NSData *pdf = [[NSData alloc]initWithBase64EncodedString:baseText options:0];
 NSString *documnet = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
 NSString *filebaseURL = [[NSString alloc]initWithString:[documnet stringByAppendingPathComponent:@"samplemade.pdf"]];
 [pdf writeToFile: filebaseURL atomically:YES];

For for additional security What I want is I want to encrypt PDF while storing in NSDocumentDirectory then decrypt it when I want to show it in UIDocumentInteraction controller. How to do this?

I got a suggestion to use FileProtection options from this link File Protection but this only protects when the device is locked. Instead I want to store this PDF in an encrypted format and while showing this PDF in my app I should decrypt it . I am using UIDocumentInteractionController. Any idea how to do this? What I want is I want to encrypt PDF while storing in NSDocumentDirectory then decrypt it when I want to show it in UIDocumentInteraction controller

1

There are 1 answers

0
M_JSL On

In my practice, the writeToFile method cannot be used to generate a pdf. If you need to make a pdf, you need to write it in Core Foundation ,you can set the password when making it, and use the UIDocumentInteractionController to read simple.pdf method interactionControllerWithURL: no password is required, if need to use a password, need to use PDFDocument to open or other methods