Cocoa Base 64 Implementation for REST Auth
2 answers
There are several options for this floating around extension NSString
or NSData
with Objective-C categories.
Here's one example that I added to the Utilities toolbar:
Title:
#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
Usage example:
NSString *inputString = @"myInputString";
NSLog(@"%@", [NSString base64StringFromData:[inputString dataUsingEncoding:NSUTF8StringEncoding]]);
+1
source to share