title: iOS AES Encryption - Fail to Encrypt
body: <p>In my project I got to implement AES 128 CBC Encryption. I am using Category and is based on NSData. This is my encryption code :</p>
  
  <pre><code>- (NSData*)AES128Decrypt
  {
      char ivPtr[kCCKeySizeAES128 + 1];
      bzero(ivPtr, sizeof(ivPtr));
  
      // fetch iv data
      [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
  
  
      // 'key' should be 32 bytes for AES256, will be null-padded otherwise
      char keyPtr[kCCKeySizeAES128 + 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];   // dataLength = 19
  
      //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, 0,
                                            keyPtr, kCCKeySizeAES128,
                                            ivPtr,
                                            [self bytes], dataLength, 
                                            buffer, bufferSize, 
                                            &amp;numBytesDecrypted);  // buffer = 0 &amp; numBytesDecrypted = 0
  
      if (cryptStatus == kCCSuccess)
      {
          //the returned NSData takes ownership of the buffer and will free it on deallocation
          return [NSData dataWithBytes:buffer length:numBytesDecrypted] ;  // returns 0
      }
  
      free(buffer); //free the buffer;
      return nil;
  }
  </code></pre>
  
  <p>And this is how I am calling it from my view class :</p>
  
  <pre><code>- (void) testActuallyEncrypting :(NSString*) hexString {
      NSLog(@"String to Encrypt : %@", hexString); // prints test12
  
      @try {
      //Convert NSString to NSData
      NSData *data = [self dataFromHexString:hexString];  // [hexString dataUsingEncoding:NSUTF8StringEncoding];  //
      // // Prepare the NSDAta obj to store the encrypted pswd
      NSData *encryptedData = [NSData dataWithBytes:[data bytes] length:[data length]];  // 6bytes
      NSData *decryptedData = [encryptedData AES128Decrypt];  // 0bytes
      NSString *decryptedString = [NSString stringWithUTF8String:[decryptedData bytes]];  // NULL Exception
      NSLog(@"Decrypted String : %@", decryptedString);
  
      decryptedString = [self addPaddingToString:decryptedString];
      decryptedData = [NSData dataWithBytes:[decryptedString UTF8String] length:[[decryptedString dataUsingEncoding:NSUTF8StringEncoding] length]];
      encryptedData = [decryptedData AES128Encrypt];
      if (encryptedData!=nil)
      {
          NSString *encryptedHexString = [self hexStringFromData:encryptedData];
          NSLog(@"Encrypted HexString : %@",encryptedHexString);
  
       }
      }@catch (NSException *ex) {
          NSLog(@"Exception : %@", ex);
      }
  }
  </code></pre>
  
  <p>I am passing <code>"test12"</code> string to be encrypted. On calling <code>AES128Decrypt</code>, <code>decryptedData</code> is 0, due to which the next line <code>decryptedString</code> throws Null exception - <code>Exception : *** +[NSString stringWithUTF8String:]: NULL cString</code>.</p>
  
  <p>Can anyone help me know why the decryptedData is null. Where am I going wrong in the AES128Decrypt method ?</p>
  
  <p>Please help me. I am stuck on this from last 2 days. Searched on this a lot on internet, but couldn't get any solution to get thru it. 
  Any help is highly appreciated. Thanks.</p>
  
  <p><strong>UPDATE :-</strong>
  Added @Zaph's method in my class and am calling it. </p>
  
  <pre><code>NSLog(@"String to Encrypt : %@", hexString);
  NSString *iv = @"fedcba9876543210";
  NSString *key = @"0123456789abcdef";
  
  // Convert str to encrypt, iv &amp; key from NSString to NSData
  NSData *dataIn = [hexString dataUsingEncoding:NSUTF8StringEncoding];
  NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
  NSData *symKey = [key dataUsingEncoding:NSUTF8StringEncoding];
  NSError *error;
  
  NSData *result = [LoginViewController doCipher:dataIn iv:ivData key:symKey context:kCCEncrypt error:&amp;error]; // result = 16bytes
  
  if (result != nil) {
      // Convert result to satring
      NSString *resultStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
      NSLog(@"Encrypted Str = %@", resultStr );  // Encrypted Str = (null)  ????
  </code></pre>
  
  <p>Why the converted string is null ? Any help please. Thanks</p>