UInt8 XOR'd array result to NSString conversio

2019-09-05 07:22发布

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?

1条回答
再贱就再见
2楼-- · 2019-09-05 08:03

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 8859-1, which is the ISO/IEC 8859-1 encoding when supplemented with the C0 and C1 control codes. It maps the Unicode code points U+0000 .. U+00FF to the bytes 0x00 .. 0xFF (compare 8859-1.TXT).

This encoding is available for (NS)String as NSISOLatin1StringEncoding.

Please note: The result of converting an arbitrary binary chunk to a (NS)String with NSISOLatin1StringEncoding will contain embedded NUL and control characters. Some functions behave unexpectedly when used with such a string. For example, NSLog() terminates the output at the first embedded NUL character. This conversion is meant to solve OP's concrete problem (creating a QR-code which is recognized by a 3rd party application). It is not meant as a universal mechanism to convert arbitrary data to a string which may be printed or presented in any way to the user.

查看更多
登录 后发表回答