0

I'm receiving data in a http header from a server which is base64 encoded and am having a problem decoding it. I've got some existing java code which I've converted to Objective-C and have determined the reason for the base 64 decoding issue is due to a difference in the UTF-8 decoding results between java and Objective-C. Here's a a java snippet replicating the java conversion:

import java.util.Base64;
public class HelloWorld{
     public static void main(String []args){
        System.out.println("Hello World");
        try {
            String s = "t%2BX";
            System.out.println(s);
            String utfDecoded = java.net.URLDecoder.decode(s, "UTF-8");
             System.out.println("Decoded UTF");
            System.out.println(utfDecoded);
            byte[] b = Base64.getDecoder().decode(utfDecoded);
             System.out.println("Decoded bytes");
            System.out.println(b);
        } catch(Exception e)  {
              System.out.println("exception");
       }
     }
}

When run the original string and decoded string is output as:

t%2BX
t+X

Now here's my Obj-C code:

NSString* utf8EncodedString = @"t%2BX";
const char *cString = [utf8EncodedString cStringUsingEncoding:NSISOLatin1StringEncoding];
NSString *decodedUTF8 = [NSString stringWithCString: cString encoding:NSUTF8StringEncoding];
NSLog(utf8EncodedString);
NSLog(decodedUTF8);
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:decodedUTF8 options: 0];

When this is run, decodedData is nil which means initWithBase64EncodedString doesn't think the input is valid base54 encoded and the output in the console is:

t2BX

t2X

How can I get the UTF-8 data decoded properly so that I can feed it to initWithBase64EncodedString?

(This isn't the full actual string that's being decoded, but I've narrowed the problem down to this small portion of it that is resulting in the call to initWithBase64EncodedString retiring nil).

(Its not a padding issue NSData won't accept valid base64 encoded string)

Community
  • 1
  • 1
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378

2 Answers2

1

Your string is in UTF8 and has URL encoding. You need to use NSString's stringByRemovingPercentEncoding method, just as in Java you are using URLDecoder. There is no need to use an intermediate C string. HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
0

Taking CRD's answer one step further, here's the code

NSString* utf8EncodedString = @"t%2BX";
NSString* decodedUTF8 = [utf8EncodedString stringByRemovingPercentEncoding];
NSLog(@"%@", utf8EncodedString);
NSLog(@"%@", decodedUTF8);
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:decodedUTF8 options: 0];

Will output

t%2BX
t+X
Peter
  • 2,005
  • 1
  • 20
  • 14