oe a
oe a

Reputation: 2280

Cannot convert NSData to NSString

I have text that I am encrypting as follows:

NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *encryptedData = [RNEncryptor encryptData:data withSettings:kRNCryptorAES256Settings password:[loggedUser getKey]error:&error];

I am then trying to to convert the string off and store it somewhere. This is what I am trying:

NSString *convertedString = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];

However the string convertedString is always null/nil even though the debugger shows me encryptedData always has data inside of it. How do I convert this to a string? Also, along the same lines, how do I convert it back into NSData to be decrypted later?

Here is an example output of the NSData I am trying to convert:

Printing description of encryptedData: <0301ff17 956167db a88cdc14 7cab1a85 28ad01c9 78c5a843 ecf22404 9c2c6915 7681277b 6e1161d8 1dd1122b 29c65f76 8bf95652 791cf2b0 3231b7b6 dbd00cb6 56301058 bfdebd9c 5edfcfe2 bc21c4fc 707a>

Upvotes: 1

Views: 885

Answers (2)

Try this:

NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding];

Most common except UTF-8 encoding is:

  • NSASCIIStringEncoding
  • NSUnicodeStringEncoding
  • NSISOLatin1StringEncoding
  • NSISOLatin2StringEncoding
  • NSSymbolStringEncoding

Upvotes: 0

Bryan Chen
Bryan Chen

Reputation: 46598

you should send NSData directly. or base64 encoded it using base64EncodedStringWithOptions:

Upvotes: 2

Related Questions