Cocoa Base 64 Implementation for REST Auth

3 Solutions Collect From Internet About “Cocoa Base 64 Implementation for REST Auth”

There should be absolutely no need for you to do this. At a high level, Cocoa provides NSURLConnection which will do HTTP authentication. If not, the CFHTTP APIs provide lower-level access.

Matt Gallagher has a good tutorial.

There are a few variants of this floating around that extend NSString or NSData through the use of Objective-C categories.

Here’s one example that I have added to my “utilities” toolbox:

Header:

#import <Foundation/NSString.h>

@interface NSString (Utilities)

+ (NSString *) base64StringFromData:(NSData *)data;

@end    

Implementation:

#import "NSString+Utilities.h"

@implementation NSString (Utilities)

+ (NSString *) base64StringFromData:(NSData *)data {
  static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  if ([data length] == 0)      
    return @"";

  char *characters = malloc((([data length] + 2) / 3) * 4);
  if (characters == NULL)
    return nil;
  NSUInteger length = 0;

  NSUInteger i = 0;
  while (i < [data length]) {
    char buffer[3] = {0,0,0};
    short bufferLength = 0;
    while (bufferLength < 3 && i < [data length])
      buffer[bufferLength++] = ((char *)[data bytes])[i++];

    //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
    characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
    characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];

    if (bufferLength > 1)
      characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
    else characters[length++] = '=';

    if (bufferLength > 2)
      characters[length++] = encodingTable[buffer[2] & 0x3F];
    else characters[length++] = '=';        
  }

  return [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSUTF8StringEncoding freeWhenDone:YES] autorelease];
}

@end

Example usage:

NSString *inputString = @"myInputString";
NSLog(@"%@", [NSString base64StringFromData:[inputString dataUsingEncoding:NSUTF8StringEncoding]]);