Created
April 2, 2014 10:24
-
-
Save buh/9931558 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSData (AES) | |
- (instancetype)aesEncryptWithKey:(NSData *)key iv:(NSData *)iv; | |
- (instancetype)aesDecryptWithKey:(NSData *)key iv:(NSData *)iv; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <CommonCrypto/CommonCryptor.h> | |
#import "NSData+AES.h" | |
@implementation NSData (AES) | |
- (instancetype)aesEncryptWithKey:(NSData *)key iv:(NSData *)iv | |
{ | |
return [self aesOperation:kCCEncrypt key:key iv:iv]; | |
} | |
- (instancetype)aesDecryptWithKey:(NSData *)key iv:(NSData *)iv | |
{ | |
return [self aesOperation:kCCDecrypt key:key iv:iv]; | |
} | |
- (instancetype)aesOperation:(CCOperation)operation key:(NSData *)key iv:(NSData *)iv | |
{ | |
if (iv && iv.length != 16) { | |
@throw [NSException exceptionWithName:@"Cocoa Security" | |
reason:@"Length of iv is wrong. Length of iv should be 16 (128bits)" | |
userInfo:nil]; | |
} | |
if (key.length != 16 && key.length != 24 && key.length != 32) { | |
@throw [NSException exceptionWithName:@"Cocoa Security" | |
reason:@"Length of key is wrong. Length of iv should be 16, 24 or 32 (128, 192 or 256bits)" | |
userInfo:nil]; | |
} | |
// Setup output buffer. | |
size_t bufferSize = [self length] + kCCBlockSizeAES128; | |
void *buffer = malloc(bufferSize); | |
size_t encryptedSize = 0; | |
CCCryptorStatus cryptStatus = CCCrypt(operation, | |
kCCAlgorithmAES128, | |
kCCOptionPKCS7Padding, | |
[key bytes], // Key | |
[key length], // kCCKeySizeAES | |
(iv ? [iv bytes] : NULL), // IV (optional) | |
[self bytes], | |
[self length], | |
buffer, | |
bufferSize, | |
&encryptedSize); | |
if (cryptStatus == kCCSuccess) { | |
return [NSData dataWithBytesNoCopy:buffer length:encryptedSize]; | |
} | |
free(buffer); | |
return nil; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Larger files crash with the memory issue.