Skip to content

Instantly share code, notes, and snippets.

@matsuda
Created February 25, 2014 07:14
Show Gist options
  • Save matsuda/9204276 to your computer and use it in GitHub Desktop.
Save matsuda/9204276 to your computer and use it in GitHub Desktop.
Objective-C code for encrypt and decrypt by AES-128 encryption.
/**
http://mythosil.hatenablog.com/entry/20111017/1318873155
http://blog.dealforest.net/2012/03/ios-android-per-aes-crypt-connection/
*/
@interface NSData (AES)
- (NSData *)AES128EncryptedDataWithKey:(NSString *)key;
- (NSData *)AES128DecryptedDataWithKey:(NSString *)key;
- (NSData *)AES128EncryptedDataWithKey:(NSString *)key iv:(NSString *)iv;
- (NSData *)AES128DecryptedDataWithKey:(NSString *)key iv:(NSString *)iv;
@end
#import "NSData+AES.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation NSData (AES)
- (NSData *)AES128EncryptedDataWithKey:(NSString *)key
{
return [self AES128EncryptedDataWithKey:key iv:nil];
}
- (NSData *)AES128DecryptedDataWithKey:(NSString *)key
{
return [self AES128DecryptedDataWithKey:key iv:nil];
}
- (NSData *)AES128EncryptedDataWithKey:(NSString *)key iv:(NSString *)iv
{
return [self AES128Operation:kCCEncrypt key:key iv:iv];
}
- (NSData *)AES128DecryptedDataWithKey:(NSString *)key iv:(NSString *)iv
{
return [self AES128Operation:kCCDecrypt key:key iv:iv];
}
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
bzero(ivPtr, sizeof(ivPtr));
if (iv) {
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
}
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
ivPtr,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
@end
@ngdinhkhoa
Copy link

how to use

@jp-dubey07
Copy link

Add #import<UIKit/UiKit.h> in header file.

@Abhishek9634
Copy link

Abhishek9634 commented Aug 29, 2016

Hello after decryption it is giving null
here the data is decrypted
theJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&theJsonError];
NSLog(@"RESPONSE_JSON :: %@",(NSString *)theJson);
LOGS : RESPONSE_JSON :: null

@thejeff77
Copy link

Any chance you can make this available to the rest of us? Apache / MIT license? By default this is copyrighted.

@Gantaios
Copy link

Abhishek9634 have you solved the issue am facing similar can you help me

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