PHP iOS AES Encryption

牧云@^-^@ 提交于 2019-11-30 19:47:23

As said in the comments, it would probably easiest for you to use HTTPS.

I once set up an iPhone app that had to communicate with a PHP backend over HTTPS, and spent many hours trying to find out why the iPhone wouldn't accept the encrypted connection.

As it turned out, it didn't work because I was using a self-signed certificate on the server side. Buying an SSL certificate from a Certificate Authority solved all issues.

SSL certificates that validate a single domain name without company or extended validation are really cheap, so I suggest you give that a try!

I just got through this same sort of project. I used the library you referenced in "also considered..."

Here is some example code to decrypt with php:

$iv2 = '';
for($i=0;$i<16;$i++){
    $iv2 .= "\0";   
}
$plain_text_CBC = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted_text, MCRYPT_MODE_CBC, $iv2);
var_dump($plain_text_CBC);

Make sure your keys are both 256-bit (32 characters, I have not yet had any encoding issues, but if you do, remember that you are encrypting bytes, not characters). Note that 128 in MCRYPT_RIJNDAEL_128 is the block size and not the key size, while in the method AES256DecryptWithKey, 256 is a reference to the key size, while the block size is 128. AES256DecryptWithKey runs in CBC mode, but has a null initialization vector (iv).

CBC means that each block depends on the last block, and so it uses a pre-set, usually random, "block -1" called the IV

ECB means that each block is encrypted in the same way, hence it reveals when two blocks in the same message are the same. The library mentioned does not use it, so I mentioned it just for contrast.

The use of a zero iv (0000000000000000 in bytes) is considered insecure. To fix this you would have to create an NSData *iv variable for the IV and modify the CCcrypt argument of NSData+AESCrypt.m to add [iv bytes] for the iv parameter (I have not yet tested this code), and you would need to store this iv and pass it to the php along with you message. But first I would test and have everything working with a zero iv.

For a direct example, my open source project "Techno Tap" contains PHP and iOS source that uses AES encryption successfully, feel free to take a look here

The encryption on iOS is done in ScoreboardManager.m (using NSData+AES) and decryption is done on the PHP side in Scoreboard.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!