PHP加密和objective-c解密

时间:2013-01-15 23:08:10

标签: php objective-c encryption

我必须在我的php服务器上生成加密密钥并将其发送到ipad应用程序进行解密。

我在php服务器端做了什么:

    $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= 

在xcode中我导入了sercurity.framwork,我为base64添加了第三方(编码和解码),我也使用了(CommonCryptor.h),这里是我的代码:

+ (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);
  }

我为strOut得到了..... :(

请帮助......

1 个答案:

答案 0 :(得分:1)

  1. 您应该为AES-128使用16字节密钥和IV。 Mcrypt_encrypt否则将其填充为零。
  2. 您最有可能手动将PKCS#5填充添加到输入,因为mcrypt_encrypt将数据填充为零,这不常见。