我在 iOS 和 PHP 之间进行加密通信时遇到问题。我有一个加密字符串并将其发送到解密它的 PHP 服务器的应用程序。那部分工作得很好。现在 PHP 服务器需要将加密的响应发送回应用程序,这似乎有点问题 更多的白发。
问题是,当我在 PHP 中加密一个字符串时,它看起来与在 iOS 甚至 .NET 中加密的相同字符串不同 - 显然所有地方都使用相同的算法、 key 和 IV。
我在 CBC 模式下使用 Rijndael 128,IV 由空字节组成(到目前为止)。
PHP 加密看起来是这样的:
$encrypted = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->secret_key, $str, MCRYPT_MODE_CBC, $this->iv );
$encrypted = base64_encode( $encrypted );
iOS加密附在这个文件中:
StringEncryption.m: http://pastie.org/1365766
我希望有人能帮我找出我遗漏了什么或有一些不同的值参数。我已经看了几个小时了,找不到其他可以尝试的东西。
最佳答案
很可能是填充问题...请参阅 here或 here获取更多信息。
EDIT 在 OP 评论之后:
除了 NULL
-padding 之外,PHP 没有对其他填充模式的内置支持。至少 .Net 允许您指定 NULL 填充(我认为),另一种选择是在 PHP 中实现 PKCS#7 填充,这并不难做到。
Pad the input with a padding string of between 1 and 8 bytes to make the total length an exact multiple of 8 bytes. The value of each byte of the padding string is set to the number of bytes added - i.e. 8 bytes of value 0x08, 7 bytes of value 0x07, ..., 2 bytes of 0x02, or one byte of value 0x01.
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $blockSize - (strlen($data) % $blockSize);
$data .= str_repeat(chr($padding), $padding);
关于php - PHP 加密与 iOS 和 .NET 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4411645/