title: RNCryptor AES256 to match PHP MCRYPT_RIJNDAEL_256
body: <p>The PHP API I’m calling from within my iOS app requires the payload to be encrypted in a certain customised way. I’m having troubles replicating that approach in Objective-C, with RNCryptor.</p>
  
  <p>Here is the PHP code used to encrypt a string:</p>
  
  <pre><code>function encrypt($string) {
      $key = 'some-random-key';
      return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
  }
  </code></pre>
  
  <p>And this how I’m trying to achieve the same encryption result in Objective-C:</p>
  
  <pre><code>+ (NSData*)encryptData:(NSData*)sourceData {
  
      NSString *keyString = @"some-random-key";
      NSData *key = [[keyString MD5String] dataUsingEncoding:NSUTF8StringEncoding];
      NSData *iv = [[[keyString MD5String] MD5String] dataUsingEncoding:NSUTF8StringEncoding];
  
      NSMutableData *encryptedData = [NSMutableData data];
  
      RNCryptorEngine *cryptor = [[RNCryptorEngine alloc] initWithOperation:kCCEncrypt settings:kRNCryptorAES256Settings key:key IV:iv error:nil];
  
      [encryptedData appendData:[cryptor addData:sourceData error:nil]];
      [encryptedData appendData:[cryptor finishWithError:nil]];
  
      return encryptedData;
  
  }
  </code></pre>
  
  <p>But the results from the two functions never match. E.g., for the same one-word string, the PHP code returns <code>J39gRcuBEaqMIPP1VlizdA8tRjmyAB6za4zG5wcOB/8=</code>, while in Objective-C (after running <code>base64EncodedStringWithOptions:</code> on the resulting NSData) I’m getting <code>1FGpZpVm2p4z3BBY6KW2fw==</code>.</p>
  
  <p>Is there something I need to further tweak in the RNCryptor settings to make it work?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I’ve played around the the native iOS CommonCrypto framework directly, without using the third party RNCryptor lib altogether. I’m consisently getting the same result as with RNCryptor though. I even tried implementing AES128 in both my Objective-C and PHP snippets, but even that never made the results from the two environments match…</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>The <code>MD5String</code> method I‘m using is a category on NSString and is defined as follows:</p>
  
  <pre><code>- (NSString *)MD5String {
      const char *cstr = [self UTF8String];
      unsigned char result[16];
      CC_MD5(cstr, strlen(cstr), result);
  
      return [[NSString stringWithFormat:
              @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
              result[0], result[1], result[2], result[3],
              result[4], result[5], result[6], result[7],
              result[8], result[9], result[10], result[11],
              result[12], result[13], result[14], result[15]
              ] lowercaseString];
  }
  </code></pre>