I am encrypting a text string using the following block of code.
This code relates to a method for AES256EncryptWithKey, but when I run the project, and I click on the button that uses this code, I get an uncaught exception and a warning. The warning says: “NSString may not respond to: ‘-AES256EncryptWithKey'”. What can I do? Is it possible to put a chunk of code in that handles exceptions? Or is it something totally different?
NSString *Input = [Inputbox text];
[Input AES256encryptWithKey];
Here is the code I have used, that relates to AES256EncryptWithKey:
@implementation NSData (AES256)
- (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];
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;
}
Thank-You in advance. Links, Tutorials, Answers, and anything else is appreciated.
Thats because
NSStringin fact does not respond to that message – your code adds a category toNSData!Remember encryption works on binary data, so you must convert your potentially unicode
NSStringinto a well-defined binary encoding (say, UTF-8)The fastest conversion is to use the NSString
dataWithEncodingmethod.