AES128 in Objective-C -> Test Case fails - objective-c

I try to get a AES128 encryption running with objective-c. However, I don't get the correct output.
This may also be a stupid objective-c error because I'm just starting with this language ;-)
My test case looks like this:
CryptoUtils* crypt = [[CryptoUtils alloc] init];
NSData* plaintext = [#"6bc1bee22e409f96e93d7e117393172a" dataUsingEncoding:NSUTF8StringEncoding];
NSData* key = [#"2b7e151628aed2a6abf7158809cf4f3c" dataUsingEncoding:NSUTF8StringEncoding];
NSData* iv = [#"000102030405060708090A0B0C0D0E0F" dataUsingEncoding:NSUTF8StringEncoding];
NSString* encrypted = [crypt encryptData:plaintext withKey:key andIV:iv];
XCTAssertEqualObjects(#"7649abac8119b246cee98e9b12e9197d", encrypted , #"AES testcase1 not equal");
The encryptData method looks like this:
(NSString *)encryptData:(NSData*)clearText withKey:(NSData*) currentKey andIV:(NSData*) currentIV{
// Buffer for Ciphertext
NSMutableData *cipherData = [NSMutableData dataWithLength:clearText.length + kCCBlockSizeAES128];
size_t cipherLength;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
currentKey.bytes,
currentKey.length,
currentIV.bytes,
clearText.bytes,
clearText.length,
cipherData.mutableBytes,
cipherData.length,
&cipherLength);
if(cryptStatus){
NSLog(#"Something terrible during encryption happened!");
} else {
NSLog(#"Ciphertext length: %i", [cipherData length]);
NSString *output=[cipherData description];
output = [output stringByReplacingOccurrencesOfString:#" " withString:#""];
output = [output stringByReplacingOccurrencesOfString:#"<" withString:#""];
output = [output stringByReplacingOccurrencesOfString:#">" withString:#""];
return output;
}
return nil;
}
Now, I'm getting back a wrong 'encrypted' String. Especially, it is a lot to long and I suspect the problem to be the NSData's that I pass to the method. Does anybody have an idea of what I'm doing wrong here?
Thank you

You meantion AES128 in your title, but refer to AES256 in your first paragraph.
It also appears that you are using input data, key and IV values that you do not mean to use.
It appears you want your input data to be 128 bits long (which would align with the block size), but in reality it is 376 bits long. This is technically acceptable, since you use padding, but context clues point to this being an oversight.
For AES128 your input key must be 128 bits long, but your key is 256 bits long. This is incorrect for AES128.
It appears you want your IV to be 128 bits long, but in reality it is 256 bits long. This is incorrect for AES - the IV must have the same length as block size, i.e. 128 bits.
Now, what you want to do instead, is probably:
char bytes[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a};
NSData *clearText = [NSData dataWithBytes:&bytes length:16];
char keyBytes[] = {0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c};
NSData* currentKey = [NSData dataWithBytes:&keyBytes length:16];
char ivBytes[16] = char ivBytes[16] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F};
NSData* currentIV = [NSData dataWithBytes:&ivBytes length:16];
These changes will give you input, key and IV values with 128 bit length.
After making these changes, output will be:
7649abac8119b246cee98e9b12e9197d8964e0b149c10b7b682e6e39aaeb731c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
The first 32 characters match those you provided. This suggests that your reference value is incomplete, and the code is working as intended.

Related

AES Encryption CryptLib in iOS 13 not working

My application uses AES 256 encryption to encrypt a string. The same code that was used before is generating a different result. This problem started when iOS 13 was released. And it happens only to applications that are shipped to the store or built with Xcode 11.
Here is the code used for the encryption:
- (NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv {
char keyPointer[kCCKeySizeAES256+2],// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
ivPointer[kCCBlockSizeAES128+2];
BOOL patchNeeded;
bzero(keyPointer, sizeof(keyPointer)); // fill with zeroes for padding
patchNeeded= ([key length] > kCCKeySizeAES256+1);
if(patchNeeded)
{
NSLog(#"Key length is longer %lu", (unsigned long)[[self md5:key] length]);
key = [key substringToIndex:kCCKeySizeAES256]; // Ensure that the key isn't longer than what's needed (kCCKeySizeAES256)
}
//NSLog(#"md5 :%#", key);
[key getCString:keyPointer maxLength:sizeof(keyPointer) encoding:NSUTF8StringEncoding];
[iv getCString:ivPointer maxLength:sizeof(ivPointer) encoding:NSUTF8StringEncoding];
if (patchNeeded) {
keyPointer[0] = '\0'; // Previous iOS version than iOS7 set the first char to '\0' if the key was longer than kCCKeySizeAES256
}
NSUInteger dataLength = [plainText length];
//see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html
// For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
size_t buffSize = dataLength + kCCBlockSizeAES128;
void *buff = malloc(buffSize);
size_t numBytesEncrypted = 0;
//refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h
//for details on this function
//Stateless, one-shot encrypt or decrypt operation.
CCCryptorStatus status = CCCrypt(kCCEncrypt, /* kCCEncrypt, etc. */
kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */
kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */
keyPointer, kCCKeySizeAES256, /* key and its length */
ivPointer, /* initialization vector - use random IV everytime */
[plainText bytes], [plainText length], /* input */
buff, buffSize,/* data RETURNED here */
&numBytesEncrypted);
if (status == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buff length:numBytesEncrypted];
}
free(buff);
return nil;
}
- (NSString *) encryptPlainTextWith:(NSString *)plainText key:(NSString *)key iv:(NSString *)iv {
return [[[[CryptLib alloc] init] encrypt:[plainText dataUsingEncoding:NSUTF8StringEncoding] key:[[CryptLib alloc] sha256:key length:32] iv:iv] base64EncodedStringWithOptions:0];
}
/**
* This function computes the SHA256 hash of input string
* #param key input text whose SHA256 hash has to be computed
* #param length length of the text to be returned
* #return returns SHA256 hash of input text
*/
- (NSString*) sha256:(NSString *)key length:(NSInteger) length{
const char *s=[key cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];
uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
NSString *hash=[out description];
hash = [hash stringByReplacingOccurrencesOfString:#" " withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#"<" withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#">" withString:#""];
if(length > [hash length])
{
return hash;
}
else
{
return [hash substringToIndex:length];
}
}
##
I would like to know if something in the code path has changed in the way it works. The method called to do the encryptions is "encryptPlainTextWith". Thanks in advance.
Inside:
- (NSString*) sha256:(NSString *)key length:(NSInteger) length
I replaced
NSString *hash=[out description];
To
NSString *hash=[out debugDescription];
And everything got back to normal. Cheers Happy coding.
Alternative Solution as per #Rob Napier
create separate function for converting NSData to Hex
#pragma mark - String Conversion
-(NSString*)hex:(NSData*)data{
NSMutableData *result = [NSMutableData dataWithLength:2*data.length];
unsigned const char* src = data.bytes;
unsigned char* dst = result.mutableBytes;
unsigned char t0, t1;
for (int i = 0; i < data.length; i ++ ) {
t0 = src[i] >> 4;
t1 = src[i] & 0x0F;
dst[i*2] = 48 + t0 + (t0 / 10) * 39;
dst[i*2+1] = 48 + t1 + (t1 / 10) * 39;
}
return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
}
After that Inside:
- (NSString*) sha256:(NSString *)key length:(NSInteger) length
I replaced
NSString *hash=[out description];
To
NSString *hash = [self hex:out];
I suspect that your key is longer than 32 UTF-8 bytes. In that case, this code is incorrect. Your patchNeeded conditional is basically creating a garbage key. The contents of buffer aren't promised if this function return returns false, but you're relying on them.
There is no secure way to truncate a key you were given, so I'm not really certain what behavior you want here. It depends on what kinds of strings you're passing.
This code is also incorrect if iv is shorter than 16 UTF-8 bytes. You'll wind up including random values from the stack. That part can be fixed with:
bzero(ivPointer, sizeof(ivPointer));
But if your previous version relied on random values, this will still be different.
Assuming you need to match the old behavior, the best way to debug this is to run your previous version in a debugger and see what keyPointer and ivPointer wind up being.
(Note that this approach to creating a key is very insecure. It's drastically shrinking the AES keyspace. How much depends on what kind of strings you're passing, but it's dramatic. You also should never reuse the same key+iv combination in two messages when using CBC, which this looks like it probably does. If possible, I recommend moving to a correct AES implementation. You can look at RNCryptor for one example of how to do that, or use RNCryptor directly if you prefer.)

implementing PBEKeySpec encryption into IOS

This is my java code. Now I want to implement same functionality in Objective-C.
int dkLen = 16;
int rounds = 1000;
PBEKeySpec keySpec = new PBEKeySpec(hashKey.toCharArray(),salt.getBytes(), rounds, dkLen * 8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return factory.generateSecret(keySpec).getEncoded();
This is my iOS implementation
- (void)getHashKey {
NSString *hash_key=#"MY_HASHKEY";
NSString *saltKey = #"MY_SALTKEY";
int dkLen = 16;
NSData *keyData = [hash_key dataUsingEncoding:NSUTF8StringEncoding];
NSData *salt = [saltKey dataUsingEncoding:NSUTF8StringEncoding];
uint rounds = 1000;
uint keySize = kCCKeySizeAES128;
NSMutableData *derivedKey = [NSMutableData dataWithLength:keySize];
CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm
keyData.bytes, // password
keyData.length, // passwordLength
salt.bytes, // salt
salt.length, // saltLen
kCCPRFHmacAlgSHA1, // PRF
rounds, // rounds
derivedKey.mutableBytes, // derivedKey
dkLen*8); // derivedKeyLen
NSString *myString = [[NSString alloc] initWithData:derivedKey encoding:NSASCIIStringEncoding];
NSLog(#"derivedKey: %#", myString);
}
Is there any problem with algorithm which i am using in iOS
Use the Common Crypto CCKeyDerivationPBKDF function with the option kCCPRFHmacAlgSHA1.
Note PBEKeySpec keyLength is in bits, CCKeyDerivationPBKDF derivedKeyLen is in bytes.
For a more detailed answer provide all input (hashKey, salt) and the output in hex dump format plus the number of rounds, output length in bytes.
See this SO answer for sample code.
Update for revised question code:
CCKeyDerivationPBKDF returns 8-bit data bytes that is essentially not characters and many are not printable even if forced into NSASCIIStringEncoding. Forcing to NSASCIIStringEncoding even if there is no error returned is incorrect and non-useful. Instead either use the returned NSData or convert to Base64 or HexASCII encoding.
Change
NSString *myString = [[NSString alloc] initWithData:derivedKey encoding:NSASCIIStringEncoding];
Output: A´Öº÷"ùïó
to
NSString * myString = [derivedKey base64EncodedStringWithOptions:0];
Output: QbTWgbr3FSL57/MfBQAz4A==
Note: 1000 rounds is generally considered insufficient, something in the 10,000 to 100,000 range should be used.
Timings on an iPhone 6S:
rounds seconds
1000 0.003
10000 0.032
100000 0.309
1000000 3.047

Decryption of base64 encoded data objective-C

I have been working on this for a while, but can not find a way to tackle the problem. Hopefully one of you can tell me what I am missing.
I am using NSURLConnection to download base64 encoded data containing AES128 encrypted data. What I have is the key, see code, and the knowledge that the first 16 characters of the encrypted data is the IV. What I want is to decode the data and then decrypt it using the key and iv extracted. This is what I have so far:
- (void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"Succeeded! Downloaded %d bytes of data", downloadData.length);
NSData *decoded_EncryptedData = [downloadData base64EncodedDataWithOptions:0];
NSString *decoded_EncryptedString = [[NSString alloc] initWithData: decoded_EncryptedData encoding:NSUTF8StringEncoding];
const void *key = #"0000000000000000000000000000000"; // key of length 32 char -> i know standard format for AES128 encryption is 16, maybe this requires 256 AES decryption
const void *iv = (__bridge const void *)([decoded_EncryptedString substringWithRange:NSMakeRange(0,16)]);
NSString *encryptedString = [decoded_EncryptedString substringWithRange:NSMakeRange(16, decoded_EncryptedString.length-16)];
// Now I have no idea what needs to happen, but from online research I found it should be something like this:
NSData encryptedData = [encryptedString dataUsingEncoding:NSUTF8StringEncoding]; // Writing it back into a data file
// Find size of returned data
size_t Size = encryptedData.length + kCCBlockSizeAES128;
// Initialise returned data
NSMutableData *decryptedData = [NSMutableData dataWithLength:Size];
// allocate variable to numBytesDecrypted
size_t numBytesDecrypted;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, KCCKeySizeAES128, iv,
[encryptedData bytes], [encryptedData length], [decryptedData bytes], [decryptedData length],
&numBytesDecrypted);
// Now I test whether the decryption process was successful:
if (cryptStatus == kCCSuccess) {
NSLog(#"Successfully decrypted);
NSString *decryptedString = [[NSString alloc] initWithData:decryptedData encoding: NSUTF8StringEncoding];
}
}
The above code does display Successfully decrypted, however the string return null and size 0. Could someone please help me solve this? I would be so grateful.
Kind regards,
Lennaert
You have many problems.
You really need to know if the encryption is AES128 or AES256.
Encryption is data based, not string based. The conversion to a string decoded_EncryptedString is incorrect not should not be done.
The key is an issue, using a string is generally a bad idea, it is expected to be data bytes. Possibly the key is specified in hex so 32 hex characters would be 128 bits. If so conversion to data will be required.
'iv' and encryptedString are strings but they should be data, this a result of 2 above.
The key is not passed to CCCrypt.
Padding is generally used since the data is rarely exactly a block size in length, you probably need to specify PKCS7 padding to CCCrypt. You need to know if padding was used and if so was it PKCS7, php for example uses non-standard padding.
If PKCS7 padding is used the result must be trimmed to the length based on the variable numBytesDecrypted. If some other padding is used that must be trimmed.
If you want more help please supply test data and the result.
Finally, try and check back more frequently.

Crypt Status does not equal kCCSuccess

I have been working on decryption for some time now and cannot get it to work. When I encrypt using the following code:
private static string Decrypt(string plainText, string completeEncodedKey, int keySize)
{
RijndealManaged aesEncryption = new RijndealManaged();
aesEncryption.KeySize = keySize; //keySize is 256
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.CBC;
aesEncryption.Padding = PaddingMode.PKCS7;
aesEncryption.IV = Convert.FromBase64String(ASCIIEncoding.ACSII.GetString(Convert.FromBase64String(completeEncodedString)).Split(',')[0]);
aesEncryption.Key = Convert.FromBase64String(ASCIIEncoding.ACSII.GetString(Convert.FromBase64String(completeEncodedString)).Split(',')[1]);
byte[] plainText = Encoding.UTF8.GetBytes(plainStr);
ICryptoTransform crypto = aesEncryption.CreateEncryptor();
byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherText);
}
passing the name "Anthony" as the plainText I get uRO2DBKAhFsOed/p10dz+w==
and I decrypt using
-(NSData *)AES256DecryptWithKey:(NSString *)key{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL/* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if(cryptStatus == kCCSuccess){
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free( buffer ); //free the buffer
return nil;
}
but I get nothing in return. The code gets up to the if(cryptStatus == kCCSuccess){ line and it does not go into the if statement. So the the decryption is returning nil.
Any help on why this is not working would be great. Thanks.
So I think you have a couple of problems here:
You are specifying an IV when encrypting, but you are leaving it
NULL when decrypting. While it's true that the IV is optional, you
must use the same one for encrypting and decrypting.
I'm pretty sure you are not parsing the key correctly when
decrypting. From what I can tell, you seem to be using a
double-base64 encoded string (for some reason) on the server. At
least, this is what I see you doing with it:
1. Base64 decoding the string.
2. Splitting the resulting string on ','.
3. Taking the first part of the split, base64 decoding it again to use as the IV.
4. Taking the second part of the split, base64 decoding it again to use as the key.
You aren't doing any of these things in the Obj-C code. And assuming that you are taking in the key in the same format, you need to. All you are doing in the Obj-C code is taking the NSString object and converting it into a C-string.

AES256 NSString Encryption in iOS

My app encrypts and decrypts (or it should) an NSString (the text to be encrypted / decrypted) with another NSString (the keyword) using aes 256-Bit Encryption. When I run my project and run the encrypt method, nothing gets encrypted the textfield just clears itself. Here is the code I have:
-(void)EncryptText {
//Declare Keyword and Text
NSString *plainText = DataBox.text;
NSString *keyword = Keyword.text;
//Convert NSString to NSData
NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
//Encrypt the Data
NSData *encryptedData = [plainData AESEncryptWithPassphrase:keyword];
//Convert the NSData back to NSString
NSString* cypherText = [[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding];
//Place the encrypted sting inside the Data Box
NSLog(#"Cipher Text: %#", cypherText);
}
The header files can be downloaded by clicking this link: ZIP File containing AES Implementation
I have been told that I need to use Base-64 encoding of my string to get any result. If this is true, then how do I do it?
I have also been told that encryption changed in iOS 5, and my app is an iOS 5+ ONLY app. If this is true, then what do I have to do to make this encryption work on iOS 5 or where can I find another AES 256-bit implementation that will work on NSString.
Why doesn't this code produce a result?
EDIT: The links below refer to an older implementation. The latest version is called RNCryptor.
Your code doesn't use iOS's built-in AES implementation. It has its own custom implementation. AESEncryptWithPassphrase: also incorrectly generates the key, throwing away most of the entropy in the passphrase.
On iOS, you should be using the CCCrypt*() functions for AES. You should also make sure that you understand what is happening in your encryption and decryption routines. It is very easy to write encryption code that looks correct (in that you cannot read the output by inspection), but is extremely insecure.
See Properly encrypting with AES with CommonCrypto for an explanation of the problems with the above implementation, and how to properly use AES on iOS. Note that iOS 5 now has CCKeyDerivationPBKDF available.
There is no requirement to Base-64 encode your string prior to encryption. Base-64 encoding is used in cases where you need to convert binary data into a form that can be easily sent over email or other places where control characters would be a problem. It converts 8-bit binary data in 7-bit ASCII data. That's not necessary or useful here.
EDIT: It is critical that you carefully read the explanation of how to use this code. It is dangerous to simply cut and paste security code and hope it works. That said, the full source to RNCryptManager is available as part of the Chapter 11 example code for iOS 5 Programming Pushing the Limits and may be helpful [EDIT: This is old code; I recommend RNCryptor now, linked at the top of the answer]. The book (which should be available next week despite what the site says) includes a much longer discussion of how to use this code, including how to improve performance and deal with very large datasets.
NSData with category just fine for AES encryption, I didnt check zip file but this should work for you;
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (AESAdditions)
- (NSData*)AES256EncryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData*)AES256DecryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end
Use it wrapper functions like ;
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}
- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
encoding:NSUTF8StringEncoding] autorelease];
}