Rupinder Rupinder - 5 months ago 7
iOS Question

How to encode/decode file in iOS

I have tried so many methods but i am not getting proper approach to encrypt the html file.

NSString *plainString = @"This string will be encrypted";
//should be provided by a user
NSLog( @"Original String: %@", path );
NSString *content = [path stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSString *encryptedString = [content dataUsingEncoding:NSUTF8StringEncoding];
NSLog( @"Encrypted String: %@", encryptedString );

Answer

Add new class with subclass of NSDATA.

Paste this code in .h file of your class:

#import <Foundation/Foundation.h>

@interface NSData (Encryption)
- (NSData *)AES256EncryptWithKey:(NSString *)key;
- (NSData *)AES256DecryptWithKey:(NSString *)key;
@end

And this in .m file of your class:

#import "NSData+Encryption.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (Encryption)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free(buffer); //free the buffer;
return nil;

}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}
@end

Now encrypt your html page like this:

NSString *key = @"YourEncryptionKey"; // should be provided by a user

        NSLog( @"Original String: %@", htmlCode );
        NSData *encryptedString = [[htmlCode dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
        NSLog(@"%@",encryptedString);

        [encryptedString writeToFile:htmlFilePath atomically:YES];
        NSString *myData = [NSString stringWithContentsOfFile:htmlFilePath];

        NSLog(@"Data : %@ ",myData);

Further decrypt the file as:

NSString *key = @"YourEncryptionKey";

NSString *decryptedString= [[NSString alloc] initWithData:[data1 AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
NSData *utf8Data = [decryptedString dataUsingEncoding:NSUTF8StringEncoding];
[utf8Data writeToFile:_pagesPath atomically:YES];

NSLog(@"%@",decryptedString);
NSError* error;
NSString *htmlContent = [NSString stringWithContentsOfFile:_pagesPath encoding:NSUTF8StringEncoding error:&error];

NSData *data = [htmlContent dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",data);

[_webview loadData:data MIMEType:@"application/xhtml+xml" textEncodingName:@"utf-8" baseURL:[NSURL URLWithString:@""]];
Comments