Skip to content

Instantly share code, notes, and snippets.

@swizzlevixen
Created April 22, 2011 05:07
Show Gist options
  • Save swizzlevixen/936065 to your computer and use it in GitHub Desktop.
Save swizzlevixen/936065 to your computer and use it in GitHub Desktop.
SSCrypto not returning Base64 decode
/*
I'm using the SSCrypto framework, but I'm just using it copied into my project source
as a class.
http://septicus.com/products/opensource/
Elsewhere in the SSCrypto class, I call this with an NSString:
*/
/**
* Set the cipher text from a base64 encoded string.
* The cipher text will be used for decryption and verifying.
**/
- (void)setCipherTextFromBase64String:(NSString*) s
{
[cipherText release];
NSData* data= [s dataUsingEncoding:NSUTF8StringEncoding];
cipherText = [data decodeBase64]; // This returns an empty NSData object
[cipherText retain];
}
/*
The NSString s gets the string fine, and is converted to the NSData data fine.
BUT, as noted, the [data decodeBase64] returns an empty NSData object (and again, yes,
there was data actually in it before I called this).
This is the method called in question. SSCrypto does rely on libcrypto.dylib and
libssl.dylib. These methods run without error, but the NSMutableData *data returned
at the end is empty, instead of the decoded data I expected. Any suggestions?
*/
// These methods are part of a Category on NSData
- (NSData *)decodeBase64
{
return [self decodeBase64WithNewLines:YES];
}
- (NSData *)decodeBase64WithNewLines:(BOOL)encodedWithNewlines
{
NSAssert1(([self length] <= INT_MAX), @"data length cannot be greater than %d", INT_MAX);
// Create a memory buffer containing Base64 encoded string data
BIO * mem = BIO_new_mem_buf((void *) [self bytes], (int) [self length]);
// Push a Base64 filter so that reading from the buffer decodes it
BIO * b64 = BIO_new(BIO_f_base64());
if (!encodedWithNewlines)
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
mem = BIO_push(b64, mem);
// Decode into an NSMutableData
NSMutableData * data = [NSMutableData data];
char inbuf[512];
int inlen;
while ((inlen = BIO_read(mem, inbuf, sizeof(inbuf))) > 0)
[data appendBytes: inbuf length: inlen];
// Clean up and go home
BIO_free_all(mem);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment