Data encoding in Objective-C and Ruby - iphone

I'm working on an iOS app using Parse, and I need to simulate their encryption flow using Ruby for the website and browser extensions I'm building for it.
For generating the salt for AES, they have the following code in the iOS app:
NSString *str = user.email;
NSData *strData = [str dataUsingEncoding: NSUTF8StringEncoding];
NSData *encryptedData = [strData AESEncryptWithPassphrase:str]; // using the same key
What's puzzling me is dataUsingEncoding: NSUTF8StringEncoding -- it's obviously encoding the string in UTF-8, but when I see it in NSLog it seems quite different. So if str was "randomemail#gmail.com", doing NSLog on strData outputs:
<72616e64 6f6d656d 61696c40 676d6169 6c2e636f 6d>
Now, how do I get that same output in Ruby? I can't get the right salt because of this ("randomemail#gmail.com".encode("UTF-8") simply returns the email as expected). How can I simulate dataUsingEncoding in Ruby to get the same exact salt, is there something I'm missing?
Thanks

Try this:
"randomemail#gmail.com".encode("UTF-8").bytes.to_a.map{ |x| x.to_s(16)}
and you will "see" what you want.
The hexadecimal representation of "randomemail#gmail.com" with UTF-8 encoding is
<72616e64 6f6d656d 61696c40 676d6169 6c2e636f 6d>
But ruby shows you the string representation, which is "randomemail#gmail.com".
They are showing the same stuff in different ways.
Check here for more information.

Related

Converting a photo data to nsstring returns nil

I'm allowing the users of my app to either take a pic or select one from their library. When selected I need to get the images' data and convert it to a string so I can send it to a web service.
The problem I'm currently having is that [NSString initWithData:] is returning nil when I have the encoding set to UTF8. I need to set it to UTF8 for the XML message.
NSString *dataString = [[NSString alloc] initWithData:UIImageJPEGRepresentation(theImage, 1.0) encoding:NSUTF8StringEncoding];
Thanks for any advice!
You can't convert an UIImage to NSString by using initWithData:encoding: method. This method is only for converting an string's data to NSString (an Text File for example).
If you are trying to convert any kind of binary data to NSString, there are some kind of encoding available. Base64 is widely used. Also your server should have the ability to decode what you've sent.
In addition, in most cases, send an image to server just need to POST it in binary as it used to be.

Problem converting NSDATA

I'm a young iPhone developer and I'm trying to write an iPhone app that syncs data from a server side app on my mac, basically text data.
I'm having trouble reading data on the iPhone side with the following:
`
(void)connectionReceived:(NSNotification *)aNotification {
NSFileHandle *incomingConnection = [[aNotification userInfo] objectForKey:NSFileHandleNotificationFileHandleItem];
[[aNotification object] acceptConnectionInBackgroundAndNotify];
NSData *receivedData = [incomingConnection availableData];
NSString *theString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
`
I need to print out theString to a text label on the iPhone, but what I get is the exact "hex code translation" of the text entered on the server side app and I don't seem to be able to convert it to char.
Can anyone help ?
I don't know the answer - but there are a few things to look at or try:
Did you try converting into something other than UTF8? (Unicode? ASCII?)
In the hex output it gives you - I assume it is giving a UTF8 representation - i.e. one 8-bit (two hex nibble) code for each character in your string. Is this the case? Are the hex codes "correct" for a UTF-8 or ASCII representation of your string?
Are there any "bad" codes in the result?
I am wondering if this is happening because there are characters (maybe even invisable ones - control characters - nulls, whatever) in your string which are making it so iOS can't do a "normal" UTF8 conversion...

NSData to NSString using initWithBytes:length:encoding

I have some image data (jpeg) I want to send from my iPhone app to my webservice. In order to do this, I'm using the NSData from the image and converting it into a string which will be placed in my JSON.
Currently, I'm doing this:
NSString *secondString = [[NSString alloc] initWithBytes:[result bytes]
length:[result length]
encoding:NSUTF8StringEncoding];
Where result is of type NSData. However, secondString appears to be null even though result length returns a real value (like 14189). I used this method since result is raw data and not null-terminated.
Am I doing something wrong? I've used this code in other areas and it seems to work fine (but those areas I'm currently using it involve text not image data).
TIA.
For binary data, better to encode it using Base64 encoding then decode it in you webservice. I use NSData+Base64 class downloaded from here, this reference was also taken from Stackoverflow, an answer made by #Ken (Thanks Ken!).
You are not converting the data to a string. You are attempting to interpret it as a UTF-8 encoded string, which will fail unless the data really is a UTF-8 encoded string. Your best bet is to encode it somehow, perhaps with Base64 as Manny suggests, and then decode it again on the server.

Convert NSData [UIImage] to a NSString

I am aware this question has been asked several times, but I was unable to find a definate answer that would best fit my situation.
I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.
This is what I have so far:
NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
[picker dismissModalViewControllerAnimated:YES];
NSString *content = [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
NSLog(#"%#", content);
The NSLog statement simply produces output as:
2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)
Obviously this isnt what I hoped to achieve, so any help would be great.
Kind Regards
You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.
Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.

Encoding issue: Cocoa Error 261?

So I'm fetching a JSON string from a php script in my iPhone app using:
NSURL *baseURL = [NSURL URLWithString:#"test.php"];
NSError *encodeError = [[NSError alloc] init];
NSString *jsonString = [NSString stringWithContentsOfURL:baseURL encoding:NSUTF8StringEncoding error:&encodeError];
NSLog(#"Error: %#", [encodeError localizedDescription]);
NSLog(#"STRING: %#", jsonString);
The JSON string validates when I test the output. Now I'm having an encoding issue. When I fetch a single echo'd line such as:
{ "testKey":"é" }
The JSON parser works fine and I am able to create a valid JSON object. However, when I fetch my 2MB JSON string, I get presented with:
Error: Operation could not be completed. (Cocoa error 261.)
and a Null string. My PHP file is UTF8 itself and I am not using utf8_encode() because that seems to double encode the data since I'm already pulling the data as NSUTF8StringEncoding. Either way, in my single-echo test, it's the approach that allowed me to successfully log \ASDAS style UTF8 escapes when building the JSON object.
What could be causing the error in the case of the larger string?
Also, I'm not sure if it makes a difference, but I'm using the php function addslashes() on my parsed php data to account for quotes and such when building the JSON string.
I'm surprised no one has mentioned using a different encoding value instead of NSUTF8StringEncoding when calling [NSString stringWithContentsOfFile:encoding:error:].
I also got Cocoa error 261 when parsing a JSON file. I just went through the list of NSString encodings until one worked. Fortunately the first one worked for me: NSASCIIStringEncoding!
You can also use NSString stringWithContentsOfFile:usedEncoding:error: to try to find the correct encoding (as described here: How to use stringWithContentsOfURL:encoding:error:?).
Don't know if this is your problem, but I just had a similar thing (stringWithContentsOfFile, no JSON), and the problem was that the file had CRLF (windows) line-endings and Western-whatever-it's-called encoding. I used SubEthaEdit to convert to LF (Mac/Unix line-endings) and UTF-8 encoding, and now everything works fine.
Encoding issue: Cocoa Error 261? I solved this issue by trying different encoding. First I was using NSUTF8 then I switched to NSASCIIStringEncoding and it worked.
NSString* path = [[NSBundle mainBundle] pathForResource: #"fileName" ofType: #"type"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",string);
For future reference, if you need to override the encoding, and you're working with streams without embedded NULs, something like this might be good (I've just written a rough sketch outline here, check this code is and does want you want before using it):
NSHTTPURLResponse* resp=nil;
NSData* jsonAsImmutableData = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://<whatever>"]]
returningResponse:&resp error:NULL];
NSMutableData*modifiedData = [NSMutableData dataWithData:jsonAsImmutableData];
char extraNulls[7] =
{0,0,0,0,0,0,0}; // is this defensive enough for your encoding?
[modifiedData appendBytes:extraNulls length:7];
NSString* jsonAsString = [NSString stringWithCString:[modifiedData bytes]
encoding:<whatever your encoding is>];
But I expect your best course of action is to check that your server is both using and claiming to use UTF-8 encoding or some other Apple iPhone supported encoding.
EDIT
altered code comment.
What helped me was just to change the physical file encoding to UTF-8. My editor had set it to the default, MacRoman, and didn't like letters with accents.