iosswiftnsdatabitwise-operators

Checksum and XOR in Swift


I worte these methods in Objective-C. They're just checksum and XOR some NSData

- (void)XOR:(NSMutableData *)inputData withKey:(NSData *)key
{
    unsigned char* inputByteData = (unsigned char*)[inputData mutableBytes];
    unsigned char* keyByteData   = (unsigned char*)[key bytes];
    for (int i = 0; i < [inputData length]; i++)
    {
        inputByteData[i] = inputByteData[i] ^ keyByteData[i % [key length]];
    }
}

- (Byte)checkSum:(NSMutableData *)data withLength:(Byte)dataLength
{
    Byte * dataByte = (Byte *)malloc(dataLength);
    memcpy(dataByte, [data bytes], dataLength);

    Byte result = 0;
    int count = 0;
    while (dataLength>0) {
        result += dataByte[count];
        dataLength--;
        count++;
    };
    result = result&0xff;
    return result&0xff;
}

However, I'm not familiar with Bitwise operators, especially in Swift, with these UnsafeMutablePointer<Void>... things.

Can anybody help me converting this ? (Basically, I need checksum and XOR functions)
One more things, should they be put in NSData/NSMutableData extension ?

Thank you.


Solution

  • Swift 3 update:

    public extension Data {
    
        public mutating func xor(key: Data) {
            for i in 0..<self.count {
                self[i] ^= key[i % key.count]
            }
        }
    
    
        public func checkSum() -> Int {
            return self.map { Int($0) }.reduce(0, +) & 0xff
        }
    }
    

    You can also create another function: xored(key: Data) -> Data.
    Then you can chain these operators: xored(key).checksum()