Search code examples
iphonecastingnsstringnsdatanslog

iPhone: strange output when casting nsdata to nsstring


I get a NSData object in return after decrypting a payload with aes128:

NSData *returnData = [ciphertext AES128DecryptWithKey:keyData withIV:ivData];

I get the following hex output when i try to NSLog this:

<2db88b73 d84599a1 5779c736 09c975b7 92750cf2 d11cb41b 19f13781 4401bc57 b2ad96c8 402e3ccf 851c0219 00aec76b>

I then try to setting it as NSString:

[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

When using NSLog() on the string i get "(null)" as output.

Can someone tell me why and where i should look for the problem?


Solution

  • Collided with the same issue some time ago, found the answer here.

    If the data is not null-terminated, you should use -initWithData:encoding:

    NSString* newStr = [[[NSString alloc] initWithData:theData
                                         encoding:NSUTF8StringEncoding] autorelease];
    

    If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

    NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
    

    (If you have ARC enabled, remove the -autorelease call.)