Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR file encryption in iOS

I am developing an ePub reader for iOS. The ePub files that I am downloading from the server are encrypted using XOR algorithm. I am getting those files as .xlsx format with the key to decrypt it. I am decrypting and loading the file to reader as follows:

  1. Load the file as NSData from the downloaded directory.
  2. Decrypting the data with the key.
  3. Writing the decrypted Data to a temporary directory.
  4. Load the file from temporary directory to the reader.

I am using AePubReader to load the file.

Here is the decrypting code:

- (NSData *)obfuscate:(NSData *)data withKey:(NSString *)key
{
     NSMutableData *result = [data mutableCopy];


    // Get pointer to data to obfuscate
    char *dataPtr = (char *) [result mutableBytes];

    // Get pointer to key data
    char *keyData = (char *) [[key dataUsingEncoding:NSUTF8StringEncoding] bytes];

    // Points to each char in sequence in the key
    char *keyPtr = keyData;
    int keyIndex = 0;

    // For each character in data, xor with current value in key
    for (int x = 0; x < [data length]; x++) 
    {
        // Replace current character in data with 
        // current character xor'd with current key value.
        // Bump each pointer to the next character
        *dataPtr = *dataPtr++ ^ *keyPtr++; 

        // If at end of key data, reset count and 
        // set key pointer back to start of key value
        if (++keyIndex == [key length])
            keyIndex = 0, keyPtr = keyData;
    }

    return result;
}

But when I am trying to load the decrypted file to the reader, I am getting an error as follows:

2012-07-30 20:45:12.652 XYX[5986:12203] ERROR: ePub not Valid
2012-07-30 20:45:12.652 XYX[5986:12203] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
*** First throw call stack:

I checked for the url path, it is not empty and even checked if file exists at path. File is existing at the specified path.

Where I might be going wrong???Any help will be appreciated. Thanks in advance.

like image 684
SINDHYA PETER Avatar asked Jul 30 '12 15:07

SINDHYA PETER


1 Answers

I solved it. As Paul commented, the problem was with:

*dataPtr = *dataPtr++ ^ *keyPtr++;

I changed it to:

*dataPtr = *dataPtr ^ *keyPtr;
        dataPtr++;
        keyPtr++;

Thank you Paul.

like image 180
SINDHYA PETER Avatar answered Oct 19 '22 09:10

SINDHYA PETER