简体   繁体   中英

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM