Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
Add Comment
Please, Sign In to add comment