Cheap Base64 Encoding in Mac OS X

With the help of the following, I was able to put together a base64-encoding technique on Mac OS X in Objective C that doesn’t rely on OpenSSL to get its job done. Works on small pieces of data, which is all I need it for, e. g. the Authorization header on a HTTP request:

NSData *xmlData;
NSString *error;
NSString *base64String;

xmlData = [NSPropertyListSerialization dataFromPropertyList:[@"userid:password" dataUsingEncoding:NSUTF8StringEncoding]
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
NSScanner *theScanner = [NSScanner scannerWithString:[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding]];

[theScanner scanUpToString:@"<data>" intoString:NULL];
[theScanner scanString:@"<data>" intoString:NULL];
[theScanner scanUpToString:@"</data>" intoString:&base64String];
NSLog(@"Base64: %@n", base64String);

Leave a Reply