Search code examples
iosnsdataxor

Is is safe to modify readonly NSData via pointer address?


I want to perform an XOR operation for NSData as below, is it safe to modify an readonly NSData like this (non ARC)? I have tried, it did work.

    @implementation NSData (Additions)

    - (void)xorWithByteKey:(Byte)keyByte
    {
        char *curDataPtr = (char *)self.bytes;

        for (int x = 0; x < self.length; x++)
        {
            *curDataPtr = *curDataPtr ^ keyByte;
            curDataPtr++;
        }
    }

    @end

Solution

  • From a look at CFData source code what you are doing seems safe. I had a quick search for references to _bytes (which is what you are accessing directly) and nothing jumped at me.

    Though do you really want to take the risk of relying on such an implementation detail? Is it too costly in your code to go via an NSMutableData copy of your data and modify that instead?

    As in this category (warning, untested):

    @interface NSData (xoring)
    - (NSData *) xorWithByteKey: (Byte) b ;
    @end
    
    @implementation NSData (xoring)
    
    - (NSData *) xorWithByteKey: (Byte) b {
    
       NSMutableData * copy = [self mutableCopy] ;
    
       char *p = (char *)copy.bytes;
    
       for (NSUInteger i = 0, length = copy.length ; i < length; ++i) {
            Byte c = *p ;
            c ^= b ;
            *p++ = c ;
        }
        return copy ;
    }
    

    @end