30/06/10

How to encrypt/decrypt using AES 256

Filed under: iPhone Dev SDK by Marc @ 08:44

Here is some code I found in iphonedevelopment.blogspot.com on how to extend NSMutableData to encrypt and decrypt using AES 256 encryption standard, very useful.


#import <CommonCrypto/CommonCryptor.h>


@implementation NSMutableData (AES256)
- (BOOL) encryptWithKey: (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];

// encrypts in-place, since this is a mutable data object
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt( kCCEncrypt, , kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self mutableBytes], [self length], /* input */
[self mutableBytes], [self length], /* output */
&numBytesEncrypted );

return ( result == kCCSuccess );
}



- (BOOL) decryptWithKey: (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];

// encrypts in-place, since this is a mutable data object
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt( kCCDecrypt, , kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self mutableBytes], [self length], /* input */
[self mutableBytes], [self length], /* output */
&numBytesEncrypted );

return ( result == kCCSuccess );
}
@end



No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Sorry, the comment form is closed at this time.