Created
April 24, 2012 17:27
-
-
Save danwood/2481732 to your computer and use it in GitHub Desktop.
Base 64 Encoding/Decoding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (NSData *)dataWithBase64EncodedString:(NSString *)base64String | |
{ | |
NSData *retVal = nil; | |
if([base64String canBeConvertedToEncoding:NSASCIIStringEncoding]) | |
{ | |
NSData *stringData = [base64String dataUsingEncoding: NSASCIIStringEncoding]; | |
/* base64 decode | |
* in -- input data | |
* inlen -- length of input data | |
* out -- output data (may be same as in, must have enough space) | |
* outmax -- max size of output buffer | |
* result: | |
* outlen -- actual output length | |
* | |
* returns SASL_BADPROT on bad base64, | |
* SASL_BUFOVER if result won't fit | |
* SASL_OK on success | |
*/ | |
char *buffer = malloc([stringData length]); | |
unsigned actualLength = 0; | |
int status = sasl_decode64([stringData bytes], [stringData length], buffer, [stringData length], &actualLength); | |
if (SASL_OK == status) | |
{ | |
retVal = [NSData dataWithBytesNoCopy:buffer length:actualLength]; | |
} | |
} | |
return retVal; | |
} | |
- (NSString *)base64Encoding | |
{ | |
NSString* retVal = nil; | |
/* base64 encode | |
* in -- input data | |
* inlen -- input data length | |
* out -- output buffer (will be NUL terminated) | |
* outmax -- max size of output buffer | |
* result: | |
* outlen -- gets actual length of output buffer (optional) | |
* | |
* Returns SASL_OK on success, SASL_BUFOVER if result won't fit | |
*/ | |
int bufSize = 4 * [self length] / 3 + 100; | |
char *buffer = malloc(bufSize); | |
unsigned actualLength = 0; | |
int status = sasl_encode64([self bytes], [self length], buffer, bufSize, &actualLength); | |
if (SASL_OK == status) | |
{ | |
retVal = [[[NSString alloc] initWithBytes: buffer length: actualLength encoding: NSASCIIStringEncoding] autorelease]; | |
} | |
// Clean up | |
free(buffer); | |
return retVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment