Saeed
Saeed

Reputation: 926

PHP encrypting and objective-c decrypting

I have to generate encrypted key on my php server and send it to the ipad app to decrypt it.

What I did in the php server side :

    $iv = mcrypt_create_iv(32);
    $privatEencryptKey = "1111";
    $data = "2222";
    $encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateEncryptKey, base64_encode($data), MCRYPT_MODE_CBC, $iv);
    $decryptedData = base64_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateEncryptkey, $encryptedData, MCRYPT_MODE_CBC, $iv));

    echo base64_encode($encryptedData); //output = WT7LorzZ1EQo2BeWxawW3Q==
    echo $decryptedData; // output = 2222
    echo base64_encode($iv); // output = fZTj4BxWSdCYQW/scUHvx9QoiTNXmxNrGWb/n7eFkR4= 

and in the xcode I import the sercurity.framwork and I added 3rd party for base64 (encoding & decoding) and I use the (CommonCryptor.h) also and here is my code :

+ (NSData *)doCipher:(NSData *)dataIn
              iv:(NSData *)iv
             key:(NSData *)symmetricKey
         context:(CCOperation)encryptOrDecrypt{
         CCCryptorStatus ccStatus   = kCCSuccess;
         size_t          cryptBytes = 0;    // Number of bytes moved to buffer.
         NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

         ccStatus = CCCrypt( encryptOrDecrypt,
                   kCCAlgorithmAES128,
                   0,
                   symmetricKey.bytes,
                   kCCKeySizeAES128,
                   iv.bytes,
                   dataIn.bytes,
                   dataIn.length,
                   dataOut.mutableBytes,
                   dataOut.length,
                   &cryptBytes);

        if (ccStatus != kCCSuccess) {
              NSLog(@"CCCrypt status: %d", ccStatus);
        }

      dataOut.length = cryptBytes;
      return dataOut;
  }

  + (void) testCipher{
        NSData *dataIn = [[@"WT7LorzZ1EQo2BeWxawW3Q==" base64DecodedString] dataUsingEncoding:NSUTF8StringEncoding];
        NSData *key = [@"1111" dataUsingEncoding:NSUTF8StringEncoding];
        NSData *iv = [[@"fZTj4BxWSdCYQW/scUHvx9QoiTNXmxNrGWb/n7eFkR4=" base64DecodedString] dataUsingEncoding:NSUTF8StringEncoding];

        NSData *dataOut = [Utils doCipher:dataIn iv:iv key:key context:kCCDecrypt];
        NSString* strOut = [[[NSString alloc] initWithData:dataOut
                                          encoding:NSUTF8StringEncoding] base64DecodedString];
        NSLog(@"%@", strOut);
  }

I got the nil for strOut..... :(

Any help please......

Upvotes: 0

Views: 458

Answers (1)

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

  1. You should use 16-byte Key and IV for AES-128. Mcrypt_encrypt otherwise pads this with zero.
  2. Most likely you should manually add PKCS#5 padding to the input since the mcrypt_encrypt pads data with zero, which is not common practice.

Upvotes: 1

Related Questions