Skip to content

Instantly share code, notes, and snippets.

@st3fan
Created February 26, 2010 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st3fan/315909 to your computer and use it in GitHub Desktop.
Save st3fan/315909 to your computer and use it in GitHub Desktop.
// CryptoViewController.m
#import "CryptoViewController.h"
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (Crypto)
- (NSData *) cipher: (CCOperation) operation withKey: (NSData *) key;
- (NSData *) cipherUsingAES128: (NSData *) key;
- (NSData *) decipherUsingAES128: (NSData *) key;
@end
@implementation NSData (Crypto)
- (NSData *) cipherUsingAES128: (NSData *) key {
return [self cipher: kCCEncrypt withKey: key];
}
- (NSData *) decipherUsingAES128: (NSData *) key {
return [self cipher: kCCDecrypt withKey: key];
}
- (NSData *) cipher: (CCOperation) operation withKey: (NSData *) key
{
int plainTextBlockSize = ([self length] + kCCBlockSizeAES128) & ~(kCCBlockSizeAES128 - 1);
unsigned char plainText[plainTextBlockSize];
bzero(plainText, plainTextBlockSize);
size_t plainTextLength;
CCCryptorStatus status = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionECBMode,
[key bytes],
kCCKeySizeAES128,
NULL,
[self bytes],
[self length],
plainText,
plainTextBlockSize,
&plainTextLength
);
if (status == kCCSuccess) {
return [NSData dataWithBytes: plainText length: plainTextLength];
} else {
return nil;
}
}
@end
@implementation CryptoViewController
- (void) testWithData: (NSData*) plain
{
NSData* key = [NSData dataWithBytes: "0123456789abcdef" length: 16];
NSData* encrypted = [plain cipherUsingAES128: key];
NSData* decrypted = [encrypted decipherUsingAES128: key];
NSLog(@" Original length = %d", [plain length]);
NSLog(@" Encrypted length = %d", [encrypted length]);
NSLog(@" Decrypted length = %d", [decrypted length]);
if ([plain length] != [decrypted length]) {
NSLog(@" Fail");
}
}
- (void) viewDidLoad
{
NSLog(@"Testing with content shorter than the block size");
[self testWithData: [NSData dataWithBytes: "Hi!" length: 3]];
NSLog(@"Testing with content equal to the block size");
[self testWithData: [NSData dataWithBytes: "01234567890abcdef" length: 16]];
NSLog(@"Testing with content equal to a multiple block size");
[self testWithData: [NSData dataWithBytes: "01234567890abcdef01234567890abcdef01234567890abcdef" length: 3*16]];
NSLog(@"Testing with content longer than the block size");
[self testWithData: [NSData dataWithBytes: "This plaintext is longer than the block size" length: 44]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment