Last active
August 29, 2015 14:13
-
-
Save krzyzanowskim/cb9e63c3e6af4497e661 to your computer and use it in GitHub Desktop.
AES128 category for NSData using CommonCrypto.
This file contains 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
// Marcin Krzyżanowski | |
#import <CommonCrypto/CommonCryptor.h> | |
@interface NSData (AES) | |
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv; | |
@end | |
@implementation NSData (AES) | |
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv | |
{ | |
int diff = kCCKeySizeAES128 - (self.length % kCCKeySizeAES128); | |
NSMutableData *adjustedData = [NSMutableData dataWithData:self]; | |
[adjustedData appendData:[[NSMutableData alloc] initWithLength:diff]]; | |
size_t bufferSize = adjustedData.length + kCCBlockSizeAES128; | |
void *buffer = malloc(bufferSize); | |
size_t numBytesEncrypted = 0; | |
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, | |
0x00, //No padding | |
[key UTF8String], kCCKeySizeAES128, | |
[iv UTF8String], | |
adjustedData.bytes, | |
adjustedData.length, | |
buffer, | |
bufferSize, | |
&numBytesEncrypted); | |
if(cryptStatus == kCCSuccess) { | |
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; | |
} | |
return nil; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment