how to implement this class

Discussion in 'iOS Programming' started by scanf, Oct 30, 2010.

  1. scanf macrumors newbie

    Joined:
    Apr 23, 2010
    #1
    i'm still fairly new to objective c and i'm trying to use the encryption class shown in the code below. the problem is i don't understand the @implementation part. this is usually the name of the class itself, but here is called NSData, which obviously already exists and is followed by (AES256), which is unfamiliar syntax to me.

    can someone explain that funky line and how i would set this code up?

    Code:
    #import <CommonCrypto/CommonCryptor.h>
    
    @implementation NSData (AES256)
    
    - (NSData *)AES256EncryptWithKey:(NSString *)key {
    	// 'key' should be 32 bytes for AES256, will be null-padded otherwise
    	char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    	bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
    	
    	// fetch key data
    	[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    	
    	NSUInteger dataLength = [self length];
    	
    	//See the doc: For block ciphers, the output size will always be less than or 
    	//equal to the input size plus the size of one block.
    	//That's why we need to add the size of one block here
    	size_t bufferSize = dataLength + kCCBlockSizeAES128;
    	void *buffer = malloc(bufferSize);
    	
    	size_t numBytesEncrypted = 0;
    	CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
    									 keyPtr, kCCKeySizeAES256,
    									 NULL /* initialization vector (optional) */,
    									 [self bytes], dataLength, /* input */
    									 buffer, bufferSize, /* output */
    									 &numBytesEncrypted);
    	if (cryptStatus == kCCSuccess) {
    		//the returned NSData takes ownership of the buffer and will free it on deallocation
    		return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    	}
    
    	free(buffer); //free the buffer;
    	return nil;
    }
    
    @end
    
    
    similar examples of this code can be found on the web, but none show the corresponding header.
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    It is an Objective-C category. It extends an existing class without subclassing: it adds capabilities to all instances of NSData.

    If you don't know this I'd suggest familiarising yourself with the Objective-C language. Apple have an excellent resource on their website. For this specific question see the Categories and Extensions but I would recommend ensuring you understand the whole document really.
     
  3. scanf thread starter macrumors newbie

    Joined:
    Apr 23, 2010
    #3
    ah, categories and extensions. a big thank you! i know i'm cheating by getting a little ahead here - just a little impatient :) thanks again.
     

Share This Page