Josh Josh - 4 years ago 290
Swift Question

UInt8 XOR'd array result to NSString conversion returns nil every time

I'm having issues working with iOS Swift 2.0 to perform an XOR on a [UInt8] and convert the XORd result to a String. I'm having to interface with a crude server that wants to do simple XOR encryption with a predefined array of UInt8 values and return that result as a String.

Using iOS Swift 2.0 Playground, create the following array:

let xorResult : [UInt8] = [24, 48, 160, 212] // XORd result
let result = NSString(bytes: xorResult, length: xorResult.count, encoding: NSUTF8StringEncoding)


The result is always nil. If you remove the 160 and 212 values from the array, NSString is not nil. If I switch to NSUTF16StringEncoding then I do not receive nil, however, the server does not support UTF16. I have tried converting the values to a hex string, then converting the hex string to NSData, then try to convert that to NSUTF8StringEncoding but still nil until I remove the 160 and 212. I know this algorithm works in Java, however in Java we're using a combination of char and StringBuilder and everything is happy. Is there a way around this in iOS Swift?

Answer Source

To store an arbitrary chunk of binary data as as a string, you need a string encoding which maps each single byte (0 ... 255) to some character. UTF-8 does not have this property, as for example 160 is the start of a multi-byte UTF-8 sequence and not valid on its own.

The simplest encoding with this property is the ISO Latin 1 aka ISO/IEC 8859-1 encoding. According to 8859-1.TXT, the Unicode characters U+0000 .. U+00FF are mapped exactly to the bytes 0x00 .. 0xFF. This encoding is available for (NS)String as NSISOLatin1StringEncoding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download