0

I'm trying to encrypt/decrypt an NSString and return the original string in the end. Here's how I convert the string to a data object:

NSData *string_data = [string dataUsingEncoding:NSUTF8StringEncoding];

And after that data has been encrypted/decrypted I want it back to the original string by doing:

NSString *to_string = [NSString stringWithCString:[decrypted_data bytes] encoding:NSUTF8StringEncoding];

The encoding seems to match, but I still get a null when I try to print out to_string to the console. I've tried all sorts of encoding settings. It doesn't seem to work.

Liban Abdulle
  • 177
  • 3
  • 12
  • possible duplicate http://stackoverflow.com/questions/6103579/nsdata-from-nskeyedarchiver-to-nsstring/17593009#17593009 Use base64Encoding – Nicolas Manzini Nov 14 '13 at 15:23
  • I do *not* think that is a possible duplicate. That question is about converting *arbitrary* data to a string for passing it around. This question is about converting decrypted data back to the original string. – Martin R Nov 14 '13 at 15:27

1 Answers1

1

Use:

NSString *to_string = [[NSString alloc] initWithData:string_data encoding:NSUTF8StringEncoding];

It is not safe to use stringWithCString because the bytes buffer you get from NSData is not guaranteed to be null-terminated.

Taum
  • 2,511
  • 18
  • 18
  • That doesn't work either, also you have to specify the encoding not just the data passed.That was the first method I've tried and setting it to `[[NSString alloc] initWithData:string_data encoding:NSUTF8StringEncoding]` didn't work either. – Liban Abdulle Nov 14 '13 at 15:27
  • 1
    @labdulle: Have you verified that the decrypted data `decrypted_data` is exactly equal to the original data `string_data`? – Martin R Nov 14 '13 at 15:30
  • 1
    That is a good question. It seems there is a problem with the decryption. I'm an idiot. – Liban Abdulle Nov 14 '13 at 15:40