Checksum and XOR in Swift

I worte these methods in Objective-C. It is just a checksum and XOR 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 am not familiar with bitwise operators, especially in Swift, with these UnsafeMutablePointer<Void> ... things.

Can someone help me convert this? (Basically, I need XOR checksums and functions)
One more thing if they should be added to the NSData/NSMutableData ?

Thanks.

+5
source share
3 answers

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 link these operators: xored(key).checksum()

0
source

UnsafeBufferPointer / UnsafeMutableBufferPointer may be what you need now. I tried to translate your code in Swift below. (But the code is poorly tested.)

 func XOR(inputData: NSMutableData, withKey key: NSData) { let b = UnsafeMutableBufferPointer<UInt8>(start: UnsafeMutablePointer(inputData.mutableBytes), count: inputData.length) let k = UnsafeBufferPointer<UInt8>(start: UnsafePointer(key.bytes), count: key.length) for i in 0..<inputData.length { b[i] ^= k[i % key.length] } } func checkSum(data: NSData) -> Int { let b = UnsafeBufferPointer<UInt8>(start: UnsafePointer(data.bytes), count: data.length) var sum = 0 for i in 0..<data.length { sum += Int(b[i]) } return sum & 0xff } 
+8
source

Updated for Swift 3:

 func xor(data: Data, with key: Data) -> Data { var xorData = data xorData.withUnsafeMutableBytes { (start: UnsafeMutablePointer<UInt8>) -> Void in key.withUnsafeBytes { (keyStart: UnsafePointer<UInt8>) -> Void in let b = UnsafeMutableBufferPointer<UInt8>(start: start, count: xorData.count) let k = UnsafeBufferPointer<UInt8>(start: keyStart, count: data.count) let length = data.count for i in 0..<xorData.count { b[i] ^= k[i % length] } } } return xorData } 
0
source

Source: https://habr.com/ru/post/1216581/


All Articles