Skip to content

Instantly share code, notes, and snippets.

@buh
Created April 2, 2014 10:24
Show Gist options
  • Save buh/9931558 to your computer and use it in GitHub Desktop.
Save buh/9931558 to your computer and use it in GitHub Desktop.
@interface NSData (AES)
- (instancetype)aesEncryptWithKey:(NSData *)key iv:(NSData *)iv;
- (instancetype)aesDecryptWithKey:(NSData *)key iv:(NSData *)iv;
@end
#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
@mukulm24
Copy link

mukulm24 commented Nov 8, 2018

Larger files crash with the memory issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment